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.
This commit is contained in:
2026-06-28 12:21:17 +02:00
parent 56015846b0
commit 6c13415b1e
19 changed files with 1260 additions and 39 deletions
+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())
+2
View File
@@ -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)
+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"
@@ -0,0 +1 @@
"""Org patents index: institution-scoped patent aggregation."""
@@ -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 [],
)
+421
View File
@@ -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,
)
@@ -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,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]
@@ -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,
)
@@ -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"
+105
View File
@@ -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<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,
);
}
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,
@@ -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,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<OrgPatentEntry>;
}
@@ -3,12 +3,25 @@
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente gefunden.</p>
<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)">
@@ -32,6 +45,10 @@
<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>
@@ -46,6 +63,27 @@
</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>
@@ -80,6 +118,10 @@
<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>
@@ -88,6 +130,21 @@
}
</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>
}
@@ -116,12 +173,16 @@
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getEpoCount() }}</span>
<span class="overview-label">EPO</span>
<span class="overview-value">{{ getInstitutionMatchCount() }}</span>
<span class="overview-label">Institution</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getUsptoCount() }}</span>
<span class="overview-label">USPTO</span>
<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>
@@ -1,6 +1,22 @@
.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 {
@@ -89,11 +105,64 @@
.patent-title {
color: #333;
font-weight: 500;
max-width: 400px;
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;
}
}
@@ -153,7 +222,7 @@
.overview-stats {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 4px;
}
@@ -1,8 +1,9 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api/model/patentEntry';
import { OrgPatentEntry } from '../../api/model/orgPatentEntry';
import { OrgPatentMatchTypeFilter } from '../../api/model/orgPatentsResponse';
import {
formatPatentDate,
getPublicationStageLabel,
@@ -13,7 +14,7 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
selector: 'app-institution-patents',
imports: [CommonModule],
imports: [CommonModule, RouterLink],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
})
@@ -22,15 +23,17 @@ export class InstitutionPatentsComponent implements OnInit {
private router = inject(Router);
private patentsApi = inject(PatentsService);
patents: PatentEntry[] = [];
filteredPatents: PatentEntry[] = [];
patents: OrgPatentEntry[] = [];
filteredPatents: OrgPatentEntry[] = [];
institutionName: string | null = null;
selectedPatent: PatentEntry | 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;
@@ -42,6 +45,7 @@ export class InstitutionPatentsComponent implements OnInit {
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;
@@ -49,22 +53,13 @@ export class InstitutionPatentsComponent implements OnInit {
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (this.isValidMatchType(matchTypeFromUrl)) {
this.activeMatchType = matchTypeFromUrl;
}
if (institutionId) {
this.loading = true;
this.error = false;
this.patentsApi.getPatentsByInstitution(institutionId, 'body').subscribe({
next: (result) => {
this.patents = result.patents ?? [];
this.institutionName = result.institution_name ?? null;
this.applyFilter();
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
},
});
this.institutionId = institutionId;
this.loadPatents(institutionId);
}
});
}
@@ -77,13 +72,28 @@ export class InstitutionPatentsComponent implements OnInit {
this.updateQueryParams();
}
setMatchType(matchType: OrgPatentMatchTypeFilter): void {
if (this.activeMatchType === matchType) {
return;
}
this.activeMatchType = matchType;
this.selectedPage = 1;
this.selectedPatent = null;
const institutionId = this.route.parent?.snapshot.paramMap.get('institutionId') ?? '';
if (institutionId) {
this.loadPatents(institutionId);
}
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.applyFilter();
this.updateQueryParams();
}
selectPatent(patent: PatentEntry): void {
selectPatent(patent: OrgPatentEntry): void {
this.selectedPatent = patent;
this.updateQueryParams();
}
@@ -93,6 +103,29 @@ export class InstitutionPatentsComponent implements OnInit {
this.router.navigate(['/patent', this.selectedPatent.patent_id]);
}
private loadPatents(institutionId: string): void {
this.loading = true;
this.error = false;
this.patentsApi
.getOrgPatentsByInstitution(institutionId, 'body', false, {
matchType: this.activeMatchType,
})
.subscribe({
next: (result) => {
this.patents = result.patents ?? [];
this.institutionName = result.institution_name ?? null;
this.applyFilter();
this.loading = false;
this.updateQueryParams();
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
private applyFilter(): void {
let patents = this.patents;
@@ -103,7 +136,7 @@ export class InstitutionPatentsComponent implements OnInit {
this.filteredPatents = this.sortPatents(patents);
}
private sortPatents(patents: PatentEntry[]): PatentEntry[] {
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
return [...patents].sort((a, b) => {
if (this.sortMode === 'date') {
return (b.publication_date ?? '').localeCompare(a.publication_date ?? '');
@@ -118,6 +151,7 @@ export class InstitutionPatentsComponent implements OnInit {
queryParams: {
filter: this.activeFilter,
sortBy: this.sortMode,
matchType: this.activeMatchType,
},
queryParamsHandling: 'merge',
replaceUrl: true,
@@ -132,7 +166,16 @@ export class InstitutionPatentsComponent implements OnInit {
return value === 'date' || value === 'title';
}
getPagedPatents(): PatentEntry[] {
private isValidMatchType(value: string | null): value is OrgPatentMatchTypeFilter {
return (
value === 'all' ||
value === 'institution' ||
value === 'name' ||
value === 'both'
);
}
getPagedPatents(): OrgPatentEntry[] {
const start = (this.selectedPage - 1) * this.pageSize;
return this.filteredPatents.slice(start, start + this.pageSize);
}
@@ -162,7 +205,23 @@ export class InstitutionPatentsComponent implements OnInit {
return this.patents.filter((p) => p.source === 'USPTO').length;
}
trackPatent(_index: number, patent: PatentEntry): string {
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,
@@ -182,7 +241,44 @@ export class InstitutionPatentsComponent implements OnInit {
return `${text.slice(0, 160).trimEnd()}…`;
}
getPublicationStageLabel(patent: PatentEntry): string | null {
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(', ');
}
}