moved getPatentById logic from allPatentsSearchClient to PatentSearchClient

This commit is contained in:
2026-07-01 14:06:48 +02:00
parent 5432d814c6
commit 7e8a796623
5 changed files with 87 additions and 106 deletions
@@ -18,11 +18,6 @@ from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClien
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
def normalize_patent_date(date_str: str) -> str:
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
async def get_all_patents(
page: int = 0,
size: int = 10,
@@ -88,67 +83,3 @@ async def get_all_patents(
size=size,
patents=patents,
)
async def _search_by_id(
client: AllPatentsSearchClient,
patent_id: str,
prefix: str | None = None,
filling_date: str | None = None
) -> list[model.PatentEntry]:
if prefix == "US":
data = await client.search_uspto(client.uspto_detail_query(patent_id, filling_date=filling_date))
return parse_uspto_hits(data)
data = await client.search_epo(client.epo_detail_query(patent_id, filling_date=filling_date))
return parse_epo_hits(data)
async def _search_by_title(
client: AllPatentsSearchClient,
title: str,
prefix: str | None = None,
filling_date: str | None = None
) -> list[model.PatentEntry]:
epo_data, uspto_data = await asyncio.gather(
client.search_epo(client.epo_title_query(title, filling_date=filling_date)),
client.search_uspto(client.uspto_title_query(title,filling_date=filling_date)),
)
return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
async def get_patent_by_id(
patent_id: str,
title: str | None = None,
prefix: str | None = None,
filling_date: str | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentEntry:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
if filling_date:
filling_date = normalize_patent_date(filling_date)
try:
patents = await _search_by_id(all_patents_client, patent_id,prefix=prefix, filling_date=filling_date)
if not patents:
patents = await _search_by_title(all_patents_client, title,prefix=prefix,filling_date=filling_date) if title else []
if not patents:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="Patent not found.",
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
await enrich_patents_classifications(patents[:1], ipc_search_client)
return patents[0]
@@ -33,13 +33,3 @@ async def get_all_patents(
year_from=year_from,
year_to=year_to,
)
@router.get(
"/patents/{patent_id}",
operation_id="getPatentById",
response_model=model.PatentEntry,
summary="Get a single patent by its identifier.",
)
async def get_patent_by_id(patent_id: str, title: str | None = None, prefix: str | None = None, filling_date: str | None = None):
return await logic.get_patent_by_id(patent_id, title=title, prefix=prefix, filling_date=filling_date)
@@ -6,21 +6,27 @@
from typing import Any
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
import httpx
import asyncio
from .. import config
from .name_matching import search_name_variants
DEFAULT_SEARCH_SIZE = 100
def remove_year(patent_number: str) -> str:
"""Remove a 4-digit year from the end of a patent number, if present."""
if len(patent_number) > 4 and patent_number[-4:].isdigit():
return patent_number[:-4]
return patent_number
def _match_name_field(field: str, name: str) -> dict[str, Any]:
"""Match a name field, including transliterated variants (Müller/Mueller)."""
variants = search_name_variants(name)
if len(variants) <= 1:
return {"match": {field: variants[0] if variants else name}}
return {"match_phrase": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {field: variant}} for variant in variants],
"should": [{"match_phrase": {field: variant}} for variant in variants],
"minimum_should_match": 1,
}
}
@@ -32,9 +38,15 @@ from inse.exceptions import MissingApiKeyError
class PatentSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self) -> dict[str, str]:
if not self.api_key:
@@ -158,9 +170,11 @@ class PatentSearchClient:
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
print("Searching EPO with payload:", payload)
return await self._search(ESIndex.EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
print("Searching USPTO with payload:", payload)
return await self._search(ESIndex.USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
@@ -172,9 +186,10 @@ class PatentSearchClient:
patent_id: str,
prefix: str,
title: str,
filling_date: str | None = None,
size: int = 1,
) -> dict[str, Any]:
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
"""Search EPO and USPTO by ID; fall back to match on title if no hits.
Args:
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
@@ -202,16 +217,28 @@ class PatentSearchClient:
return epo_result if epo_hits > 0 else uspto_result
if prefix.upper() == "US":
payload = self._uspto_query_by_title(title, size)
payload = self._uspto_query_by_title(title, filling_date, size)
return await self.search_uspto(payload)
payload = self._epo_query_by_title(title, size)
payload = self._epo_query_by_title(title,filling_date, size)
return await self.search_epo(payload)
#query builders
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
raw_id = patent_id.upper().removeprefix("EP")
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"doc_number": raw_id}},
{"term": {"doc_number": remove_year(raw_id)}},
{"term": {"application_number": remove_year(raw_id)}},
{"term": {"application_number": raw_id}},
],
"minimum_should_match": 1,
}
}
return {
"size": size,
"_source": [
@@ -220,11 +247,23 @@ class PatentSearchClient:
"application_filing_date", "title_en", "title_de", "abstract",
"inventors_name", "applicants_name", "ipc", "cpc",
],
"query": {"term": {"doc_number": raw_id}},
"query": query,
}
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
"""Term query against publication_number; tries the ID as-is."""
raw_id = patent_id.upper().removeprefix("US")
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"publication_number": raw_id}},
{"term": {"publication_number": remove_year(raw_id)}},
{"term": {"application_number": raw_id}},
{"term": {"application_number": remove_year(raw_id)}},
],
"minimum_should_match": 1,
}
}
return {
"size": size,
"track_total_hits": True,
@@ -235,11 +274,24 @@ class PatentSearchClient:
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": {"term": {"publication_number": patent_id}},
"query": query,
}
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title_en (and title_de as a should clause)."""
def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
"""match fallback on title_en (and title_de as a should clause)."""
query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
{"match_phrase": {"title_fr": title}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": size,
"_source": [
@@ -248,20 +300,19 @@ class PatentSearchClient:
"application_filing_date", "title_en", "title_de", "abstract",
"inventors_name", "applicants_name", "ipc", "cpc",
],
"query": {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
{"match_phrase": {"title_fr": title}},
],
"minimum_should_match": 1,
}
},
"query": query
}
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title."""
def _uspto_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
"""match fallback on title."""
query: dict[str, Any] = {
"bool": {
"should": [{"match_phrase": {"title": title}}],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": size,
"_source": [
@@ -270,5 +321,5 @@ class PatentSearchClient:
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": {"match_phrase": {"title": title}},
}
"query": query,
}
+9 -3
View File
@@ -1,5 +1,5 @@
"""Backward-compatible re-exports."""
from inse.patents.all.logic import get_all_patents, get_patent_by_id
from inse.patents.all.logic import get_all_patents
from inse.patents.authors.logic import get_patents_by_author_id
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
from inse.patents.institutions.logic import (
@@ -20,22 +20,28 @@ from .elastic_search_all_patents_client import AllPatentsSearchClient
from .ipc_search_client import IpcSearchClient
from .ipc_lookup import extract_ipc_symbol
from .name_matching import name_matches
from datetime import datetime
logger = logging.getLogger(__name__)
def normalize_patent_date(date_str: str) -> str:
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
async def get_patent(
patent_id: str,
title: str,
prefix: str,
filling_date: str | None = None,
client: PatentSearchClient | None = None,
) -> model.PatentEntry:
search_client = client or PatentSearchClient()
if filling_date:
filling_date = normalize_patent_date(filling_date)
data = await search_client.get_by_id_or_title(
patent_id=patent_id,
prefix=prefix,
title=title,
filling_date=filling_date,
)
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
+4 -1
View File
@@ -40,8 +40,11 @@ async def get_patent_by_identifier(
description="Do we want to fallback to title search if ID and DOI dont work?"
),
] = "",
filling_date: Annotated[
Optional[str], Query(description="Filling date in YYYY-MM-DD format")
] = "",
) -> model.PatentEntry | None:
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title)
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date)
@patents_router.get(