feat(patents): show OpenAlex topic labels for patent IPC/CPC codes
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Enriches patents with matched OpenAlex topic names from patents_openalex_keywords, shown alongside classifications on the patent detail page. Also fixes lookup() using a broken GET on doc ids containing "/" (400 from the gateway) by switching to a _search with an ids query. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"""Business logic for global patent listing."""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
@@ -12,13 +13,17 @@ from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.parsing import (
|
||||
enrich_patents_classifications,
|
||||
enrich_patents_openalex_topics,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
)
|
||||
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
@@ -187,4 +192,12 @@ async def get_patent_by_id(
|
||||
) from exc
|
||||
|
||||
await enrich_patents_classifications(patents[:1], ipc_search_client)
|
||||
try:
|
||||
await enrich_patents_openalex_topics(
|
||||
patents[:1], PatentsOpenAlexKeywordsClient()
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Failed to enrich patent with OpenAlex topics", exc_info=True
|
||||
)
|
||||
return patents[0]
|
||||
|
||||
@@ -32,6 +32,7 @@ class PatentEntry(BaseModel):
|
||||
cpc: list[str] = Field(default_factory=list)
|
||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
openalex_topics: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
|
||||
@@ -8,6 +8,7 @@ from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.ipc_lookup import extract_ipc_symbol
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -189,6 +190,49 @@ async def enrich_patents_classifications(
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
async def enrich_patents_openalex_topics(
|
||||
patents: list[model.PatentEntry],
|
||||
keywords_client: PatentsOpenAlexKeywordsClient,
|
||||
) -> None:
|
||||
"""Attaches OpenAlex topic labels matched to each patent's ipc/cpc codes.
|
||||
|
||||
Looks up each unique symbol once (in parallel) against
|
||||
patents_openalex_keywords, then fans the results back out per patent.
|
||||
"""
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
if raw
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
docs = await asyncio.gather(
|
||||
*(keywords_client.lookup_symbol(symbol) for symbol in symbols),
|
||||
return_exceptions=True,
|
||||
)
|
||||
topics_by_symbol: dict[str, list[str]] = {
|
||||
symbol: [
|
||||
match.get("topic_display_name")
|
||||
for match in doc.get("topic_matches") or []
|
||||
if match.get("topic_display_name")
|
||||
]
|
||||
for symbol, doc in zip(symbols, docs)
|
||||
if doc and not isinstance(doc, BaseException)
|
||||
}
|
||||
|
||||
for patent in patents:
|
||||
seen: set[str] = set()
|
||||
topics: list[str] = []
|
||||
for raw in (*patent.ipc, *patent.cpc):
|
||||
for name in topics_by_symbol.get(extract_ipc_symbol(raw), []):
|
||||
if name not in seen:
|
||||
seen.add(name)
|
||||
topics.append(name)
|
||||
patent.openalex_topics = topics[:6]
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import asyncio
|
||||
|
||||
from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.common.parsing import enrich_patents_openalex_topics
|
||||
|
||||
|
||||
class _FakeKeywordsClient:
|
||||
def __init__(self, docs: dict[str, dict]):
|
||||
self.docs = docs
|
||||
self.lookup_calls: list[str] = []
|
||||
|
||||
async def lookup_symbol(self, symbol: str):
|
||||
self.lookup_calls.append(symbol)
|
||||
return self.docs.get(symbol)
|
||||
|
||||
|
||||
def _patent(patent_id: str, ipc: list[str], cpc: list[str] | None = None) -> PatentEntry:
|
||||
return PatentEntry(patent_id=patent_id, source="EPO", ipc=ipc, cpc=cpc or [])
|
||||
|
||||
|
||||
def test_enrich_patents_openalex_topics_attaches_and_dedupes() -> None:
|
||||
client = _FakeKeywordsClient(
|
||||
{
|
||||
"C07K 11/02": {
|
||||
"topic_matches": [
|
||||
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
|
||||
{"topic_id": "https://openalex.org/T2", "topic_display_name": "Peptide Chemistry"},
|
||||
]
|
||||
},
|
||||
"A61K 38/00": {
|
||||
"topic_matches": [
|
||||
{"topic_id": "https://openalex.org/T3", "topic_display_name": "Drug Delivery"},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI", "A61K 38/00 20060101ALI"])
|
||||
|
||||
asyncio.run(enrich_patents_openalex_topics([patent], client))
|
||||
|
||||
assert patent.openalex_topics == ["Peptide Chemistry", "Drug Delivery"]
|
||||
|
||||
|
||||
def test_enrich_patents_openalex_topics_skips_unmatched_symbols() -> None:
|
||||
client = _FakeKeywordsClient({})
|
||||
patent = _patent("EP2", ipc=["Z99Z 99/99"])
|
||||
|
||||
asyncio.run(enrich_patents_openalex_topics([patent], client))
|
||||
|
||||
assert patent.openalex_topics == []
|
||||
|
||||
|
||||
def test_enrich_patents_openalex_topics_looks_up_each_symbol_once() -> None:
|
||||
client = _FakeKeywordsClient(
|
||||
{
|
||||
"C07K 11/02": {
|
||||
"topic_matches": [
|
||||
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
patents = [
|
||||
_patent("EP1", ipc=["C07K 11/02 20060101AFI"]),
|
||||
_patent("EP2", ipc=["C07K 11/02 20060101ALI"]),
|
||||
]
|
||||
|
||||
asyncio.run(enrich_patents_openalex_topics(patents, client))
|
||||
|
||||
assert client.lookup_calls == ["C07K 11/02"]
|
||||
assert patents[0].openalex_topics == ["Peptide Chemistry"]
|
||||
assert patents[1].openalex_topics == ["Peptide Chemistry"]
|
||||
@@ -23,12 +23,14 @@ from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.common.parsing import (
|
||||
deduplicate_patents,
|
||||
enrich_patents_classifications,
|
||||
enrich_patents_openalex_topics,
|
||||
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.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.org.elastic_search_client import (
|
||||
OrgPatentsSearchClient,
|
||||
fetch_authors_by_institution_name,
|
||||
@@ -420,6 +422,15 @@ async def get_org_patents_by_institution_id(
|
||||
detail="org_patents search request failed.",
|
||||
) from exc
|
||||
|
||||
try:
|
||||
await enrich_patents_openalex_topics(
|
||||
patents, PatentsOpenAlexKeywordsClient()
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Failed to enrich org_patents with OpenAlex topics", exc_info=True
|
||||
)
|
||||
|
||||
return OrgPatentsResponse(
|
||||
institution_id=short_id,
|
||||
institution_name=institution_name,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
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.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
|
||||
|
||||
|
||||
@@ -137,14 +137,21 @@ class PatentsOpenAlexKeywordsClient:
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_doc/{doc_id}",
|
||||
# Doc ids like "subgroup:C07K11/02" contain a "/", which breaks
|
||||
# GET .../_doc/{id} through the gateway in front of this cluster
|
||||
# (it mangles the path before ES sees it). A _search with an ids
|
||||
# query sends the id in the request body instead, sidestepping
|
||||
# the issue.
|
||||
response = await client.post(
|
||||
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json={"size": 1, "query": {"ids": {"values": [doc_id]}}},
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
response.raise_for_status()
|
||||
return response.json().get("_source")
|
||||
hits = response.json().get("hits", {}).get("hits", [])
|
||||
return hits[0].get("_source") if hits else None
|
||||
|
||||
async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_lookup_uses_search_with_ids_query_not_doc_get():
|
||||
"""Doc ids like "subgroup:C07K11/02" contain a "/", which breaks a GET to
|
||||
.../_doc/{id} through the gateway in front of this cluster. lookup() must
|
||||
use _search with an ids query (id goes in the body, not the URL) instead.
|
||||
"""
|
||||
captured: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
captured.append(request)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"hits": [
|
||||
{"_id": "subgroup:C07K11/02", "_source": {"ipc_label": "cyclic"}}
|
||||
]
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
client = PatentsOpenAlexKeywordsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
doc = await client.lookup("subgroup", "C07K 11/02")
|
||||
|
||||
assert len(captured) == 1
|
||||
request = captured[0]
|
||||
assert request.method == "POST"
|
||||
assert request.url.path.endswith(f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search")
|
||||
body = json.loads(request.content)
|
||||
assert body["query"] == {"ids": {"values": ["subgroup:C07K11/02"]}}
|
||||
assert doc == {"ipc_label": "cyclic"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_lookup_returns_none_when_no_hits():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
|
||||
client = PatentsOpenAlexKeywordsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
doc = await client.lookup("subgroup", "Z99Z99/99")
|
||||
|
||||
assert doc is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_lookup_symbol_stops_at_first_matching_level():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
requested_id = body["query"]["ids"]["values"][0]
|
||||
if requested_id == "group:C07K11/02":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"hits": {"hits": [{"_id": requested_id, "_source": {"ipc_label": "match"}}]}},
|
||||
)
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
|
||||
client = PatentsOpenAlexKeywordsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
doc = await client.lookup_symbol("C07K 11/02")
|
||||
|
||||
assert doc == {"ipc_label": "match"}
|
||||
@@ -30,6 +30,7 @@ export interface OrgPatentEntry {
|
||||
cpc?: Array<string>;
|
||||
cpc_descriptions?: Array<IpcClassification>;
|
||||
country?: string | null;
|
||||
openalex_topics?: Array<string>;
|
||||
institution_id: string;
|
||||
institution_name?: string | null;
|
||||
match_type: OrgPatentEntry.MatchTypeEnum;
|
||||
|
||||
@@ -30,5 +30,6 @@ export interface PatentEntry {
|
||||
cpc?: Array<string>;
|
||||
cpc_descriptions?: Array<IpcClassification>;
|
||||
country?: string | null;
|
||||
openalex_topics?: Array<string>;
|
||||
}
|
||||
|
||||
|
||||
@@ -120,6 +120,20 @@
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (patent.openalex_topics?.length) {
|
||||
<section class="card">
|
||||
<div class="section-title">
|
||||
<mat-icon>topic</mat-icon>
|
||||
<h2>OpenAlex Themen</h2>
|
||||
</div>
|
||||
<div class="tags">
|
||||
@for (topic of patent.openalex_topics; track topic) {
|
||||
<span>{{ topic }}</span>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (patent.ipc_descriptions?.length) {
|
||||
<section class="card classification-card-section classification-card-section--ipc">
|
||||
<div class="section-title">
|
||||
|
||||
Reference in New Issue
Block a user