diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 90be603e..c7f128ed 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -1,3 +1,13 @@ +ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/ +ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ + +LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ +LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 +LLM_MODEL=gemma4-e4b + +# Patent search (EPO + USPTO) +PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic +PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ @@ -6,4 +16,4 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 -LLM_MODEL=gemma4-e4b \ No newline at end of file +LLM_MODEL=gemma4-e4b diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index c72e5db4..80335dab 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -39,6 +39,11 @@ class Settings(BaseSettings): openalex_api_key: Optional[str] = None openalex_api_timeout_seconds: float = 30.0 + # Patent elasticsearch config + patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic" + patent_elasticsearch_api_key: str = "" + + # LLM config llm_api_url: Optional[str] = None llm_api_key: Optional[str] = None diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index a91e13ad..7dae7575 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -24,6 +24,10 @@ from inse.persons.service import router as persons_service_router from inse.projects.router import router as projects_router from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router +from inse.persons.service import router as persons_service_router +from inse.funders.service import router as funders_service_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 @@ -51,6 +55,7 @@ app.include_router(funders_service_router) app.include_router(company_connections_router) app.include_router(service_router) app.include_router(account_router) +app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) diff --git a/service/src/main/inse/patents/__init__.py b/service/src/main/inse/patents/__init__.py new file mode 100644 index 00000000..d10d63ca --- /dev/null +++ b/service/src/main/inse/patents/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Patents domain package. +""" diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py new file mode 100644 index 00000000..64d5865e --- /dev/null +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for patent searches in EPO and USPTO Elasticsearch indices. +""" +from typing import Any + +import httpx + +from .. import config +from .name_matching import search_name_variants + +EPO_INDEX = "epo_index_1.0" +USPTO_INDEX = "uspto_patents_3.0" + +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, + } + } + + +class MissingApiKeyError(Exception): + pass + + +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", + "title_en", + "title_de", + "abstract", + "inventors_name", + "applicants_name", + "ipc", + "ipc_text", + ], + "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", + "title", + "abstract", + "inventors_names", + "inventors_names_text", + "assignees_orgs", + "ipcr", + "ipcr_text", + ], + "query": query, + } + + 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() diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py new file mode 100644 index 00000000..7e82cc31 --- /dev/null +++ b/service/src/main/inse/patents/logic.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Business logic for patent matching by author name. +""" +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 ..persons import logic as person_logic +from ..models.openalex.author import Author +from . import model +from .elastic_search_client import MissingApiKeyError +from .elastic_search_client import PatentSearchClient +from .name_matching import name_matches + +logger = logging.getLogger(__name__) + + +async def get_patents_by_author_id( + author_id: str, + client: PatentSearchClient | None = None, +) -> model.PatentsByAuthorResponse: + search_client = client or PatentSearchClient() + + 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) + + 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): + import asyncio + 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 [] + 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, + inventors=inventors if isinstance(inventors, list) else [inventors], + assignees=applicants if isinstance(applicants, list) else [applicants], + ipc=ipc if isinstance(ipc, list) else [ipc], + 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 [] + 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, + inventors=inventors if isinstance(inventors, list) else [inventors], + assignees=assignees if isinstance(assignees, list) else [assignees], + ipc=ipc if isinstance(ipc, list) else [ipc], + country=src.get("country", "US"), + )) + return patents + + +def _filter_patents_by_name( + patents: list[model.PatentEntry], + first_name: str, + last_name: str, +) -> list[model.PatentEntry]: + """Keep patents where at least one inventor matches the author name.""" + 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 \ No newline at end of file diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py new file mode 100644 index 00000000..31ebc18c --- /dev/null +++ b/service/src/main/inse/patents/model.py @@ -0,0 +1,20 @@ +from pydantic import BaseModel, Field + + +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 + inventors: list[str] = Field(default_factory=list) + assignees: list[str] = Field(default_factory=list) + ipc: list[str] = 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] diff --git a/service/src/main/inse/patents/name_matching.py b/service/src/main/inse/patents/name_matching.py new file mode 100644 index 00000000..659b295c --- /dev/null +++ b/service/src/main/inse/patents/name_matching.py @@ -0,0 +1,242 @@ +#!/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"), +) + +# 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"), +) + + +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) + ) diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py new file mode 100644 index 00000000..53a27446 --- /dev/null +++ b/service/src/main/inse/patents/service.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + REST API for patent matching by author. +""" +from fastapi import APIRouter +from . import logic +from . 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) diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py new file mode 100644 index 00000000..08729ea6 --- /dev/null +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -0,0 +1,49 @@ +import httpx +import pytest + +from inse.patents.elastic_search_client import ( + DEFAULT_SEARCH_SIZE, + EPO_INDEX, + PatentSearchClient, + USPTO_INDEX, +) + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_epo_query_uses_nested_search_and_name_variants(): + client = PatentSearchClient(api_key="test-key") + payload = client.epo_query_by_inventor("Müller", "Christian") + + assert payload["size"] == DEFAULT_SEARCH_SIZE + assert payload["sort"][0] == {"_score": {"order": "desc"}} + nested = payload["query"]["nested"] + assert nested["path"] == "inventors_name_nested" + must = nested["query"]["bool"]["must"] + assert len(must) == 2 + assert "should" in must[0]["bool"] + + +def test_uspto_index_is_3_0(): + assert USPTO_INDEX == "uspto_patents_3.0" + assert EPO_INDEX == "epo_index_1.0" + + +@pytest.mark.anyio +async def test_search_epo_posts_to_correct_index(): + requests: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request.url.path) + return httpx.Response(200, json={"hits": {"hits": []}}) + + transport = httpx.MockTransport(handler) + client = PatentSearchClient(api_key="test-key", transport=transport) + + await client.search_epo(client.epo_query_by_inventor("Weber", "Christian")) + + assert len(requests) == 1 + assert requests[0].endswith(f"/{EPO_INDEX}/_search") diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py new file mode 100644 index 00000000..cc93465d --- /dev/null +++ b/service/src/main/inse/patents/test_name_matching.py @@ -0,0 +1,123 @@ +import pytest + +from inse.patents.name_matching import ( + first_name_match_kind, + name_matches, + name_token_variants, + normalize_name_part, + search_name_variants, + tokens_equal, +) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("Müller", "Mueller"), + ("Müller", "Muller"), + ("Schöning", "Schoening"), + ("François", "Francois"), + ("José", "Jose"), + ("García", "Garcia"), + ("Bräun", "Braun"), + ("Straß", "Strass"), + ("Grøn", "Gron"), + ("Małgorzata", "Malgorzata"), + ("Øystein", "Oystein"), + ], +) +def test_tokens_equal_transliteration(left: str, right: str) -> None: + assert tokens_equal(left, right) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("Christian", "Marc"), + ("Weber", "Wagner"), + ("Müller", "Meier"), + ], +) +def test_tokens_equal_rejects_different_names(left: str, right: str) -> None: + assert not tokens_equal(left, right) + + +def test_hyphenated_first_name() -> None: + assert tokens_equal("Jean-Pierre", "Jean Pierre") + assert tokens_equal("Jean-Pierre", "JeanPierre") + + +@pytest.mark.parametrize( + ("inventor", "first", "last", "expected"), + [ + ("Christian Weber", "Christian", "Weber", True), + ("Weber, Christian", "Christian", "Weber", True), + ("Marc Christian Weber", "Christian", "Weber", False), + ("Müller, Hans", "Hans", "Müller", True), + ("Mueller, Hans", "Hans", "Müller", True), + ("Hans Mueller", "Hans", "Müller", True), + ("Weber, Christian Hans", "Christian", "Weber", True), + ("Schoening, Klaus", "Klaus", "Schöning", True), + ], +) +def test_name_matches(inventor: str, first: str, last: str, expected: bool) -> None: + assert name_matches(inventor, first, last) is expected + + +def test_normalize_name_part_strips_diacritics() -> None: + assert normalize_name_part("François") == "francois" + assert normalize_name_part(" O'Brien ") == "obrien" + + +def test_search_name_variants_includes_transliterations() -> None: + variants = search_name_variants("Müller") + folded = {v.casefold() for v in variants} + assert "müller" in folded or "Müller".casefold() in folded + assert "mueller" in folded + assert "muller" in folded + + +def test_name_token_variants_mueller() -> None: + variants = name_token_variants("Mueller") + assert "mueller" in variants + assert "muller" in variants + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("C", "Christian"), + ("C.", "Christian"), + ("Christian", "C"), + ], +) +def test_tokens_equal_initials(left: str, right: str) -> None: + assert tokens_equal(left, right) + + +def test_tokens_equal_initials_not_for_last_names_by_default() -> None: + assert not tokens_equal("W", "Weber", allow_initial=False) + + +@pytest.mark.parametrize( + ("inventor", "first", "last", "expected"), + [ + ("C. Weber", "Christian", "Weber", True), + ("Weber, C.", "Christian", "Weber", True), + ("Weber, C", "Christian", "Weber", True), + ], +) +def test_name_matches_initials(inventor: str, first: str, last: str, expected: bool) -> None: + assert name_matches(inventor, first, last) is expected + + +def test_first_name_match_kind() -> None: + assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full" + assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial" + assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none" + + +def test_search_name_variants_includes_initial() -> None: + variants = search_name_variants("Christian") + assert "C" in variants + diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts new file mode 100644 index 00000000..5d3f6b9d --- /dev/null +++ b/webapp/src/app/api/api/patents.service.ts @@ -0,0 +1,159 @@ +/** + * Innovation Search Engine API + */ +/* 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 { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +export interface PatentEntry { + patent_id: string; + source: string; + title: string | null; + abstract: string | null; + publication_date: string | null; + publication_year: string | null; + inventors: string[]; + assignees: string[]; + ipc: string[]; + country: string | null; + confidence_score: number; +} + +export interface PatentsByAuthorResponse { + author_id: string; + author_name: string | null; + patent_count: number; + patents: PatentEntry[]; +} + +type GetPatentsByAuthorOptions = { + 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); + } + + /** + * Get patents by author. + * @endpoint get /api/inse-service/authors/{author_id}/patents + * @param authorId + * @param observe + * @param reportProgress + */ + public getPatentsByAuthor( + authorId: string, + observe?: 'body', + reportProgress?: boolean, + options?: GetPatentsByAuthorOptions, + ): Observable; + public getPatentsByAuthor( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: GetPatentsByAuthorOptions, + ): Observable>; + public getPatentsByAuthor( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: GetPatentsByAuthorOptions, + ): Observable>; + public getPatentsByAuthor( + authorId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: GetPatentsByAuthorOptions, + ): Observable { + 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 32b49d9d..7976278b 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -199,6 +199,13 @@ export const routes: Routes = [ (mod) => mod.PersonFundingComponent, ), }, + { + path: 'patents', + loadComponent: () => + import('./modules/person-patents/person-patents.component').then( + (mod) => mod.PersonPatentsComponent, + ), + }, { path: 'company-connections', loadComponent: () => diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html new file mode 100644 index 00000000..34f6189c --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -0,0 +1,179 @@ +@if (loading) { +

Lade Patente...

+} @else if (error) { +

Fehler beim Laden der Patente.

+} @else if (patents.length === 0) { +

Keine Patente gefunden.

+} @else { +
+
+

+ {{ filteredPatents.length }} + Patente +

+

+ {{ getEpoCount() }} + EPO +

+

+ {{ getUsptoCount() }} + USPTO +

+
+ + @if (showDetail && selectedPatent) { + + } + +
+ @if (showDetail && selectedPatent) { +
+

{{ selectedPatent.title ?? selectedPatent.patent_id }}

+ + @if (selectedPatent.abstract) { +
+

Abstract

+

{{ selectedPatent.abstract }}

+
+ } + +
+

Erfinder

+
    + @for (inventor of selectedPatent.inventors; track inventor) { +
  • {{ inventor }}
  • + } +
+
+ + @if (selectedPatent.assignees.length > 0) { +
+

Anmelder

+
    + @for (assignee of selectedPatent.assignees; track assignee) { +
  • {{ assignee }}
  • + } +
+
+ } + + @if (selectedPatent.ipc.length > 0) { +
+

Klassifikation (IPC)

+
    + @for (ipc of selectedPatent.ipc; track ipc) { +
  • {{ ipc }}
  • + } +
+
+ } +
+ } + +
+
+ + +
+ + + + + + + + + + + @for (patent of getPagedPatents(); track patent.patent_id) { + + + + + + } + +
PatentQuelleJahr
+ {{ patent.title ?? patent.patent_id }} + + + {{ patent.source }} + + {{ patent.publication_year ?? '-' }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedPatent) { +
+

{{ selectedPatent.title ?? selectedPatent.patent_id }}

+
+
+ Quelle + + + {{ selectedPatent.source }} + + +
+
+ Patent-Nr. + {{ selectedPatent.patent_id }} +
+
+ Datum + {{ + formatDate(selectedPatent.publication_date) + }} +
+
+
+ } @else { +
+

Klicke auf ein Patent für Details.

+
+ } +
+
+} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss new file mode 100644 index 00000000..59079610 --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -0,0 +1,306 @@ +.message { + padding: 16px; + color: #666; +} + +.patents-container { + padding: 16px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.patents-summary { + margin-bottom: 8px; + display: flex; + gap: 24px; + + .summary-line { + margin: 0; + font-size: 14px; + color: #333; + } + + .summary-label { + color: #333; + } + + .summary-value { + font-weight: 600; + color: #333; + } +} + +.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: 400px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + } +} + +.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; + } + + 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; + } + } +} + +.stat--clickable { + cursor: pointer; + transition: + border-color 0.15s, + background 0.15s; + + &:hover { + border-color: #0b63ce; + background: #f0f6ff; + } +} + +.patent-full-detail { + flex: 1; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 20px; + background: #fafafa; + + h3 { + margin: 0 0 16px 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 { + border: none; + background: none; + color: #333; + cursor: pointer; + font-size: 14px; + font-weight: 400; + padding: 0; + align-self: flex-start; // NEU + + &:hover { + text-decoration: underline; + } +} + +.detail-section { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #eee; +} + +.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; +} + +.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; + } +} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts new file mode 100644 index 00000000..0b6246d3 --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -0,0 +1,165 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router } from '@angular/router'; +import { PatentsService, PatentEntry } from '../../api/api/patents.service'; + +type SortMode = 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-person-patents', + imports: [CommonModule], + templateUrl: './person-patents.component.html', + styleUrl: './person-patents.component.scss', +}) +export class PersonPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: PatentEntry[] = []; + filteredPatents: PatentEntry[] = []; + authorName: string | null = null; + selectedPatent: PatentEntry | null = null; + showDetail = false; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + sortMode: SortMode = 'date'; + + selectedPage = 1; + readonly pageSize = 10; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const authorId = params.get('id') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.showDetail = false; + this.applyFilter(); + this.updateQueryParams(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.applyFilter(); + this.updateQueryParams(); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent = patent; + this.showDetail = false; + this.updateQueryParams(); + } + + openDetail(): void { + this.showDetail = true; + } + + private applyFilter(): void { + let patents = this.patents; + + if (this.activeFilter !== 'all') { + patents = patents.filter((p) => p.source === this.activeFilter); + } + + this.filteredPatents = this.sortPatents(patents); + } + + private sortPatents(patents: PatentEntry[]): PatentEntry[] { + return [...patents].sort((a, b) => { + if (this.sortMode === 'date') { + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); + } + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); + }); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + }, + 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'; + } + + getPagedPatents(): PatentEntry[] { + const start = (this.selectedPage - 1) * this.pageSize; + return this.filteredPatents.slice(start, start + this.pageSize); + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); + } + + hasPagination(): boolean { + return this.getPageCount() > 1; + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.updateQueryParams(); + } + + formatDate(date: string | null): string { + if (!date) return '-'; + const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); + return new Intl.DateTimeFormat('de-DE').format(new Date(d)); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index edc7f00d..2e25628a 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -218,6 +218,7 @@ export class PersonComponent { { label: 'Netzwerk', path: 'network', disabled: false }, { label: 'Unternehmen', path: 'company-connections', disabled: false }, { label: 'Förderungen', path: 'funding', disabled: false }, + { label: 'Patente', path: 'patents', disabled: false }, ]; onInterestingTagClick(selection: { id: string; name: string }): void {