From 6c13415b1e5dde7fc19946bc6cc4cab975218fbe Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 28 Jun 2026 12:19:46 +0200 Subject: [PATCH] Add org_patents indexing and institution patent match-type UI 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. --- service/scripts/index_org_patents.py | 38 ++ service/src/main/inse/main.py | 2 + .../src/main/inse/middleware/etag_cache.py | 20 +- service/src/main/inse/model.py | 1 + service/src/main/inse/patents/org/__init__.py | 1 + .../inse/patents/org/elastic_search_client.py | 195 ++++++++ service/src/main/inse/patents/org/logic.py | 421 ++++++++++++++++++ service/src/main/inse/patents/org/mapping.py | 33 ++ service/src/main/inse/patents/org/model.py | 27 ++ service/src/main/inse/patents/org/service.py | 38 ++ .../src/main/inse/patents/org/test_logic.py | 100 +++++ webapp/src/app/api/api/patents.service.ts | 105 +++++ webapp/src/app/api/model/matchedAuthor.ts | 4 + webapp/src/app/api/model/models.ts | 3 + webapp/src/app/api/model/orgPatentEntry.ts | 11 + .../src/app/api/model/orgPatentsResponse.ts | 10 + .../institution-patents.component.html | 71 ++- .../institution-patents.component.scss | 73 ++- .../institution-patents.component.ts | 146 ++++-- 19 files changed, 1260 insertions(+), 39 deletions(-) create mode 100644 service/scripts/index_org_patents.py create mode 100644 service/src/main/inse/patents/org/__init__.py create mode 100644 service/src/main/inse/patents/org/elastic_search_client.py create mode 100644 service/src/main/inse/patents/org/logic.py create mode 100644 service/src/main/inse/patents/org/mapping.py create mode 100644 service/src/main/inse/patents/org/model.py create mode 100644 service/src/main/inse/patents/org/service.py create mode 100644 service/src/main/inse/patents/org/test_logic.py create mode 100644 webapp/src/app/api/model/matchedAuthor.ts create mode 100644 webapp/src/app/api/model/orgPatentEntry.ts create mode 100644 webapp/src/app/api/model/orgPatentsResponse.ts diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py new file mode 100644 index 00000000..7eb03cef --- /dev/null +++ b/service/scripts/index_org_patents.py @@ -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()) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index ca69d84c..4df7111e 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -32,6 +32,7 @@ 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.org.service import router as org_patents_router from inse.patents.service import ( institution_patents_router, patents_router as patents_all_router, @@ -53,6 +54,7 @@ app = FastAPI( ) 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) diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 547aecb4..03e54dc5 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -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, diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 028d5eb7..a6c922bb 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -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" diff --git a/service/src/main/inse/patents/org/__init__.py b/service/src/main/inse/patents/org/__init__.py new file mode 100644 index 00000000..89bdee15 --- /dev/null +++ b/service/src/main/inse/patents/org/__init__.py @@ -0,0 +1 @@ +"""Org patents index: institution-scoped patent aggregation.""" diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py new file mode 100644 index 00000000..4266471b --- /dev/null +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -0,0 +1,195 @@ +"""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 = 500 + + +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", + size: int = DEFAULT_PAGE_SIZE, + ) -> list[OrgPatentEntry]: + 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"}}) + + payload = { + "size": size, + "track_total_hits": True, + "query": {"bool": {"filter": filters}}, + } + + 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 [] + response.raise_for_status() + data = response.json() + + patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])] + patents.sort( + key=lambda patent: ( + int(patent.publication_year) if patent.publication_year and patent.publication_year.isdigit() else 0, + patent.patent_id, + ), + reverse=True, + ) + return patents + + +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 [], + ) diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py new file mode 100644 index 00000000..f242ed90 --- /dev/null +++ b/service/src/main/inse/patents/org/logic.py @@ -0,0 +1,421 @@ +"""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", + 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 = await org_patents_client.search_by_institution( + institution_id=short_id, + match_type=match_type, + ) + 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=len(patents), + patents=patents, + ) diff --git a/service/src/main/inse/patents/org/mapping.py b/service/src/main/inse/patents/org/mapping.py new file mode 100644 index 00000000..d3191a46 --- /dev/null +++ b/service/src/main/inse/patents/org/mapping.py @@ -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"}, + }, + }, + } +} diff --git a/service/src/main/inse/patents/org/model.py b/service/src/main/inse/patents/org/model.py new file mode 100644 index 00000000..e557aaf8 --- /dev/null +++ b/service/src/main/inse/patents/org/model.py @@ -0,0 +1,27 @@ +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 + patents: list[OrgPatentEntry] diff --git a/service/src/main/inse/patents/org/service.py b/service/src/main/inse/patents/org/service.py new file mode 100644 index 00000000..46e7c708 --- /dev/null +++ b/service/src/main/inse/patents/org/service.py @@ -0,0 +1,38 @@ +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", +) -> OrgPatentsResponse: + return await logic.get_org_patents_by_institution_id( + institution_id=id, + match_type=match_type, + institutions_client=client, + ) diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py new file mode 100644 index 00000000..ca01887e --- /dev/null +++ b/service/src/main/inse/patents/org/test_logic.py @@ -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" diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 68ad4460..8c8d1f41 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -14,6 +14,7 @@ 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; @@ -34,6 +35,13 @@ type GetPatentsByInstitutionOptions = { transferCache?: boolean; }; +type GetOrgPatentsByInstitutionOptions = { + matchType?: OrgPatentMatchTypeFilter; + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; +}; + @Injectable({ providedIn: 'root', }) @@ -222,6 +230,103 @@ export class PatentsService extends BaseService { ); } + public getOrgPatentsByInstitution( + institutionId: string, + observe?: 'body', + reportProgress?: boolean, + options?: GetOrgPatentsByInstitutionOptions, + ): Observable; + public getOrgPatentsByInstitution( + institutionId: string, + observe?: 'response', + reportProgress?: boolean, + options?: GetOrgPatentsByInstitutionOptions, + ): Observable>; + public getOrgPatentsByInstitution( + institutionId: string, + observe?: 'events', + reportProgress?: boolean, + options?: GetOrgPatentsByInstitutionOptions, + ): Observable>; + public getOrgPatentsByInstitution( + institutionId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: GetOrgPatentsByInstitutionOptions, + ): Observable { + 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, + ); + } + + 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + public getAllPatents( page: number = 0, size: number = 10, diff --git a/webapp/src/app/api/model/matchedAuthor.ts b/webapp/src/app/api/model/matchedAuthor.ts new file mode 100644 index 00000000..058da26a --- /dev/null +++ b/webapp/src/app/api/model/matchedAuthor.ts @@ -0,0 +1,4 @@ +export interface MatchedAuthor { + openalex_author_id: string; + author_name: string; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c91170db..a210c254 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -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'; diff --git a/webapp/src/app/api/model/orgPatentEntry.ts b/webapp/src/app/api/model/orgPatentEntry.ts new file mode 100644 index 00000000..50cfcef8 --- /dev/null +++ b/webapp/src/app/api/model/orgPatentEntry.ts @@ -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[]; +} diff --git a/webapp/src/app/api/model/orgPatentsResponse.ts b/webapp/src/app/api/model/orgPatentsResponse.ts new file mode 100644 index 00000000..7cba08c5 --- /dev/null +++ b/webapp/src/app/api/model/orgPatentsResponse.ts @@ -0,0 +1,10 @@ +import { OrgPatentEntry } from './orgPatentEntry'; + +export type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; + +export interface OrgPatentsResponse { + institution_id: string; + institution_name?: string | null; + patent_count: number; + patents: Array; +} diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 335eca55..0c13fff1 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -3,12 +3,25 @@ } @else if (error) {

Fehler beim Laden der Patente.

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

Keine Patente gefunden.

+

Keine Patente in org_patents für diese Institution gefunden.

+

+ Der Index muss zuerst befüllt werden: + python service/scripts/index_org_patents.py --institution-id {{ institutionId }} +

} @else {
+