Merge branch 'ts-136-patent-to-researchers-v2' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details
This commit is contained in:
@@ -97,13 +97,15 @@ class PatentSearchClient:
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"ipc_text",
|
||||
"cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
@@ -150,13 +152,17 @@ class PatentSearchClient:
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"inventors_names_text",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"ipcr_text",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
@@ -179,4 +185,4 @@ class PatentSearchClient:
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return response.json()
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Parse IPC/CPC symbols and assemble enriched classification objects.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import model
|
||||
|
||||
IPC_SYMBOL_RE = re.compile(
|
||||
r"^(?P<section>[A-HY])"
|
||||
r"(?P<class_num>\d{2})"
|
||||
r"(?P<subclass_letter>[A-Z])"
|
||||
r"\s*"
|
||||
r"(?:(?P<main_group>\d+))?"
|
||||
r"(?:/(?P<subgroup>\d+))?"
|
||||
r"\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# EPO strings append metadata after the symbol, e.g.
|
||||
# "G01S 5/02 20100101AFI20140127BHEP"
|
||||
IPC_CODE_EXTRACT_RE = re.compile(
|
||||
r"^([A-HY]\d{2}[A-Z]\s*\d+(?:/\d+)?)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Legacy EPO spacing and trailing classification value, e.g.
|
||||
# "C 07C 405/00 A" or "C 07D 317/20 B"
|
||||
EPO_LEGACY_IPC_RE = re.compile(
|
||||
r"^(?P<section>[A-HY])\s+"
|
||||
r"(?P<class_num>\d{2})\s*"
|
||||
r"(?P<subclass_letter>[A-Z])\s+"
|
||||
r"(?P<main_group>\d+)"
|
||||
r"(?:/(?P<subgroup>\d+))?"
|
||||
r"(?:\s+(?P<classification_value>[A-Z]))?"
|
||||
r"(?:\s|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
IPC_SUBCLASS_ONLY_RE = re.compile(
|
||||
r"^([A-HY]\d{2}[A-Z])(?:\s|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IpcHierarchyKeys:
|
||||
symbol: str
|
||||
normalized: str
|
||||
section: str | None
|
||||
ipc_class: str | None
|
||||
subclass: str | None
|
||||
main_group: str | None
|
||||
subgroup: str | None
|
||||
|
||||
|
||||
def extract_ipc_symbol(raw: str) -> str:
|
||||
"""
|
||||
Extract the classification code from a raw patent IPC string.
|
||||
|
||||
Supports:
|
||||
- 'G01S 5/02 20100101AFI20140127BHEP'
|
||||
- 'C 07C 405/00 A' (legacy EPO spacing)
|
||||
"""
|
||||
cleaned = raw.strip()
|
||||
if not cleaned:
|
||||
return cleaned
|
||||
|
||||
legacy = EPO_LEGACY_IPC_RE.match(cleaned)
|
||||
if legacy:
|
||||
section = legacy.group("section").upper()
|
||||
class_num = legacy.group("class_num")
|
||||
subclass_letter = legacy.group("subclass_letter").upper()
|
||||
prefix = f"{section}{class_num}{subclass_letter}"
|
||||
main_group = legacy.group("main_group")
|
||||
subgroup = legacy.group("subgroup")
|
||||
if subgroup is not None:
|
||||
normalized = f"{prefix}{main_group}/{subgroup}"
|
||||
else:
|
||||
normalized = f"{prefix}{main_group}"
|
||||
return display_ipc_symbol(normalized)
|
||||
|
||||
match = IPC_CODE_EXTRACT_RE.match(cleaned)
|
||||
if match:
|
||||
return display_ipc_symbol(normalize_ipc_symbol(match.group(1)))
|
||||
|
||||
match = IPC_SUBCLASS_ONLY_RE.match(cleaned)
|
||||
if match:
|
||||
return match.group(1).upper()
|
||||
|
||||
return cleaned
|
||||
|
||||
|
||||
def normalize_ipc_symbol(symbol: str) -> str:
|
||||
"""Remove whitespace, e.g. 'H01L 21/02' -> 'H01L21/02'."""
|
||||
return re.sub(r"\s+", "", symbol.strip().upper())
|
||||
|
||||
|
||||
def display_ipc_symbol(normalized: str) -> str:
|
||||
"""Format for display, e.g. 'H01L21/02' -> 'H01L 21/02'."""
|
||||
match = re.match(r"^([A-HY]\d{2}[A-Z])(\d+)(/\d+)$", normalized, re.IGNORECASE)
|
||||
if match:
|
||||
return f"{match.group(1)} {match.group(2)}{match.group(3)}"
|
||||
match = re.match(r"^([A-HY]\d{2}[A-Z])$", normalized, re.IGNORECASE)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return normalized
|
||||
|
||||
|
||||
def parse_ipc_symbol(symbol: str) -> IpcHierarchyKeys:
|
||||
"""Derive lookup keys for each hierarchy level from a patent IPC symbol."""
|
||||
cleaned = extract_ipc_symbol(symbol.strip())
|
||||
normalized = normalize_ipc_symbol(cleaned)
|
||||
match = IPC_SYMBOL_RE.match(cleaned) or IPC_SYMBOL_RE.match(normalized)
|
||||
|
||||
if not match:
|
||||
return IpcHierarchyKeys(
|
||||
symbol=cleaned,
|
||||
normalized=normalized,
|
||||
section=None,
|
||||
ipc_class=None,
|
||||
subclass=None,
|
||||
main_group=None,
|
||||
subgroup=None,
|
||||
)
|
||||
|
||||
section = match.group("section").upper()
|
||||
class_num = match.group("class_num")
|
||||
subclass_letter = match.group("subclass_letter").upper()
|
||||
subclass = f"{section}{class_num}{subclass_letter}"
|
||||
ipc_class = f"{section}{class_num}"
|
||||
|
||||
main_group_digits = match.group("main_group")
|
||||
subgroup_digits = match.group("subgroup")
|
||||
|
||||
main_group = None
|
||||
subgroup = None
|
||||
if main_group_digits:
|
||||
base = f"{subclass}{main_group_digits}"
|
||||
if subgroup_digits:
|
||||
full = f"{base}/{subgroup_digits}"
|
||||
if len(subgroup_digits) > 2:
|
||||
subgroup = full
|
||||
main_group = f"{base}/{subgroup_digits[:2]}"
|
||||
else:
|
||||
main_group = full
|
||||
else:
|
||||
main_group = base
|
||||
|
||||
return IpcHierarchyKeys(
|
||||
symbol=cleaned,
|
||||
normalized=normalized,
|
||||
section=section,
|
||||
ipc_class=ipc_class,
|
||||
subclass=subclass,
|
||||
main_group=main_group,
|
||||
subgroup=subgroup,
|
||||
)
|
||||
|
||||
|
||||
def _format_level(number: str | None, name: str | None) -> str | None:
|
||||
if not number or not name:
|
||||
return None
|
||||
label = display_ipc_symbol(number)
|
||||
return f"{label} - {name.strip()}"
|
||||
|
||||
|
||||
def _lookup_name(level_names: dict[str, str | None], *keys: str | None) -> str | None:
|
||||
for key in keys:
|
||||
if not key:
|
||||
continue
|
||||
if key in level_names and level_names[key]:
|
||||
return level_names[key]
|
||||
normalized = normalize_ipc_symbol(key)
|
||||
if normalized in level_names and level_names[normalized]:
|
||||
return level_names[normalized]
|
||||
return None
|
||||
|
||||
|
||||
def build_ipc_classification(
|
||||
keys: IpcHierarchyKeys,
|
||||
names: dict[str, dict[str, str | None]],
|
||||
) -> model.IpcClassification:
|
||||
"""Combine parsed keys with lookup results from the ipc index."""
|
||||
section_name = _lookup_name(names.get("section", {}), keys.section)
|
||||
class_name = _lookup_name(names.get("class", {}), keys.ipc_class)
|
||||
subclass_name = _lookup_name(names.get("class", {}), keys.subclass)
|
||||
group_name = _lookup_name(
|
||||
names.get("group", {}),
|
||||
keys.main_group,
|
||||
keys.normalized,
|
||||
)
|
||||
subgroup_name = _lookup_name(
|
||||
names.get("subgroup", {}),
|
||||
keys.subgroup,
|
||||
keys.normalized,
|
||||
)
|
||||
|
||||
if not subgroup_name and group_name and keys.subgroup:
|
||||
subgroup_name = group_name
|
||||
|
||||
main_group = None
|
||||
if group_name:
|
||||
main_group = _format_level(keys.main_group or keys.normalized, group_name)
|
||||
|
||||
subgroup = None
|
||||
if subgroup_name:
|
||||
subgroup = _format_level(keys.subgroup or keys.normalized, subgroup_name)
|
||||
|
||||
return model.IpcClassification(
|
||||
symbol=keys.symbol,
|
||||
section=_format_level(keys.section, section_name),
|
||||
ipc_class=_format_level(keys.ipc_class, class_name)
|
||||
if class_name
|
||||
else (display_ipc_symbol(keys.ipc_class) if keys.ipc_class else None),
|
||||
subclass=_format_level(keys.subclass, subclass_name),
|
||||
main_group=main_group,
|
||||
subgroup=subgroup,
|
||||
)
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for IPC/CPC classification lookups in the ipc Elasticsearch index.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from .ipc_lookup import IpcHierarchyKeys
|
||||
from .ipc_lookup import build_ipc_classification
|
||||
from .ipc_lookup import parse_ipc_symbol
|
||||
|
||||
IPC_INDEX = "ipc"
|
||||
|
||||
_LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
("section", "cpc_section_number", "cpc_section_name"),
|
||||
("class", "cpc_class_number", "cpc_class_name"),
|
||||
("group", "cpc_group_number", "cpc_group_name"),
|
||||
("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"),
|
||||
)
|
||||
|
||||
|
||||
class IpcSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
async def resolve_symbols(self, symbols: list[str]) -> dict[str, model.IpcClassification]:
|
||||
"""Resolve patent IPC symbols to enriched classification objects."""
|
||||
unique_symbols = list(dict.fromkeys(s.strip() for s in symbols if s and s.strip()))
|
||||
if not unique_symbols:
|
||||
return {}
|
||||
|
||||
parsed = {symbol: parse_ipc_symbol(symbol) for symbol in unique_symbols}
|
||||
names = await self._lookup_all_levels(parsed.values())
|
||||
|
||||
return {
|
||||
symbol: build_ipc_classification(keys, names)
|
||||
for symbol, keys in parsed.items()
|
||||
}
|
||||
|
||||
async def _lookup_all_levels(
|
||||
self,
|
||||
keys_list: list[IpcHierarchyKeys],
|
||||
) -> dict[str, dict[str, str | None]]:
|
||||
symbols_by_level: dict[str, set[str]] = {
|
||||
"section": set(),
|
||||
"class": set(),
|
||||
"group": set(),
|
||||
"subgroup": set(),
|
||||
}
|
||||
|
||||
for keys in keys_list:
|
||||
if keys.section:
|
||||
symbols_by_level["section"].add(keys.section)
|
||||
if keys.ipc_class:
|
||||
symbols_by_level["class"].add(keys.ipc_class)
|
||||
if keys.subclass:
|
||||
symbols_by_level["class"].add(keys.subclass)
|
||||
if keys.main_group:
|
||||
symbols_by_level["group"].add(keys.main_group)
|
||||
if keys.subgroup:
|
||||
symbols_by_level["subgroup"].add(keys.subgroup)
|
||||
if "/" in keys.normalized:
|
||||
symbols_by_level["group"].add(keys.normalized)
|
||||
symbols_by_level["subgroup"].add(keys.normalized)
|
||||
|
||||
results: dict[str, dict[str, str | None]] = {
|
||||
level: {} for level in symbols_by_level
|
||||
}
|
||||
|
||||
for level, number_field, name_field in _LEVELS:
|
||||
level_symbols = {s for s in symbols_by_level[level] if s}
|
||||
if level_symbols:
|
||||
results[level] = await self._lookup_level(number_field, name_field, level_symbols)
|
||||
|
||||
return results
|
||||
|
||||
async def _lookup_level(
|
||||
self,
|
||||
number_field: str,
|
||||
name_field: str,
|
||||
symbols: set[str],
|
||||
) -> dict[str, str | None]:
|
||||
if not symbols:
|
||||
return {}
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"size": min(len(symbols), 100),
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}}
|
||||
for symbol in sorted(symbols)
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
"_source": [number_field, name_field],
|
||||
}
|
||||
|
||||
data = await self._search(payload)
|
||||
found: dict[str, str | None] = {}
|
||||
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
number = source.get(number_field)
|
||||
if not number:
|
||||
continue
|
||||
normalized_number = number.strip().upper()
|
||||
found[normalized_number] = source.get(name_field)
|
||||
found[number.strip()] = source.get(name_field)
|
||||
|
||||
return found
|
||||
|
||||
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{IPC_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -15,6 +15,8 @@ from ..models.openalex.author import Author
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from .ipc_search_client import IpcSearchClient
|
||||
from .ipc_lookup import extract_ipc_symbol
|
||||
from .name_matching import name_matches
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -23,8 +25,10 @@ logger = logging.getLogger(__name__)
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = _get_author(author_id)
|
||||
if not author:
|
||||
@@ -63,6 +67,10 @@ async def get_patents_by_author_id(
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
all_patents = _deduplicate_patents(all_patents)
|
||||
|
||||
await _enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
@@ -87,6 +95,7 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
@@ -94,9 +103,13 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=src.get("application_filing_date"),
|
||||
kind=src.get("kind"),
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=applicants if isinstance(applicants, list) else [applicants],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
@@ -109,6 +122,7 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
@@ -116,14 +130,67 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||
application_type=src.get("application_type"),
|
||||
number_of_claims=src.get("number_of_claims"),
|
||||
status=src.get("status"),
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=assignees if isinstance(assignees, list) else [assignees],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
items = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||
|
||||
|
||||
def _descriptions_for_raw_codes(
|
||||
raw_codes: list[str],
|
||||
resolved: dict[str, model.IpcClassification],
|
||||
) -> list[model.IpcClassification]:
|
||||
return [
|
||||
resolved[extract_ipc_symbol(raw)]
|
||||
for raw in raw_codes
|
||||
if extract_ipc_symbol(raw) in resolved
|
||||
]
|
||||
|
||||
|
||||
async def _enrich_patents_classifications(
|
||||
patents: list[model.PatentEntry],
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> None:
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
try:
|
||||
resolved = await ipc_client.resolve_symbols(symbols)
|
||||
except MissingApiKeyError:
|
||||
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||
return
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning("Classification enrichment failed: %s", exc)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||
return
|
||||
|
||||
for patent in patents:
|
||||
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
@@ -136,6 +203,31 @@ def _filter_patents_by_name(
|
||||
]
|
||||
|
||||
|
||||
def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||
"""Remove exact duplicate hits while keeping distinct publication stages."""
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.PatentEntry] = []
|
||||
|
||||
for patent in patents:
|
||||
key = _patent_dedup_key(patent)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
deduplicated.append(patent)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
stage = patent.kind or patent.application_type or ""
|
||||
return (
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date or "",
|
||||
stage,
|
||||
)
|
||||
|
||||
|
||||
def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = person_logic.search_persons(author_id=short_id)
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class IpcClassification(BaseModel):
|
||||
symbol: str
|
||||
section: str | None = None
|
||||
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
||||
subclass: str | None = None
|
||||
main_group: str | None = None
|
||||
subgroup: str | None = None
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
|
||||
class PatentEntry(BaseModel):
|
||||
@@ -8,13 +19,23 @@ class PatentEntry(BaseModel):
|
||||
abstract: str | None = None
|
||||
publication_date: str | None = None
|
||||
publication_year: str | None = None
|
||||
application_number: str | None = None
|
||||
application_date: str | None = None
|
||||
kind: str | None = None # EPO only
|
||||
application_type: str | None = None # USPTO only
|
||||
number_of_claims: int | None = None # USPTO only
|
||||
status: str | None = None # USPTO only
|
||||
inventors: list[str] = Field(default_factory=list)
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = Field(default_factory=list)
|
||||
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
cpc: list[str] = Field(default_factory=list)
|
||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
author_id: str
|
||||
author_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
patents: list[PatentEntry]
|
||||
@@ -0,0 +1,129 @@
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_lookup import (
|
||||
build_ipc_classification,
|
||||
display_ipc_symbol,
|
||||
extract_ipc_symbol,
|
||||
normalize_ipc_symbol,
|
||||
parse_ipc_symbol,
|
||||
)
|
||||
from inse.patents.model import IpcClassification
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw", "normalized"),
|
||||
[
|
||||
("H01L 21/02", "H01L21/02"),
|
||||
("h01l21/02", "H01L21/02"),
|
||||
("H04L 29/08", "H04L29/08"),
|
||||
],
|
||||
)
|
||||
def test_normalize_ipc_symbol(raw: str, normalized: str) -> None:
|
||||
assert normalize_ipc_symbol(raw) == normalized
|
||||
|
||||
|
||||
def test_display_ipc_symbol() -> None:
|
||||
assert display_ipc_symbol("H01L21/02") == "H01L 21/02"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_main_group() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/02")
|
||||
assert keys.section == "H"
|
||||
assert keys.ipc_class == "H01"
|
||||
assert keys.subclass == "H01L"
|
||||
assert keys.main_group == "H01L21/02"
|
||||
assert keys.subgroup is None
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_subgroup() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/0262")
|
||||
assert keys.main_group == "H01L21/02"
|
||||
assert keys.subgroup == "H01L21/0262"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_epo_string() -> None:
|
||||
raw = "G01S 5/02 20100101AFI20140127BHEP"
|
||||
assert extract_ipc_symbol(raw) == "G01S 5/02"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_cpc_string() -> None:
|
||||
raw = "A61B 5/0713 20130101AFI20140127BHEP"
|
||||
assert extract_ipc_symbol(raw) == "A61B 5/0713"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_from_epo_string() -> None:
|
||||
keys = parse_ipc_symbol("G01S 5/02 20100101AFI20140127BHEP")
|
||||
assert keys.symbol == "G01S 5/02"
|
||||
assert keys.section == "G"
|
||||
assert keys.subclass == "G01S"
|
||||
assert keys.main_group == "G01S5/02"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_subclass_only() -> None:
|
||||
assert extract_ipc_symbol("H01L extra") == "H01L"
|
||||
|
||||
|
||||
def test_build_ipc_classification_uses_index_names() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/02")
|
||||
names = {
|
||||
"section": {"H": "ELECTRICITY"},
|
||||
"class": {"H01L": "SEMICONDUCTOR DEVICES"},
|
||||
"group": {"H01L21/02": "Manufacture or treatment of semiconductor devices"},
|
||||
"subgroup": {},
|
||||
}
|
||||
|
||||
result = build_ipc_classification(keys, names)
|
||||
|
||||
assert result.symbol == "H01L 21/02"
|
||||
assert result.section == "H - ELECTRICITY"
|
||||
assert result.subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
assert result.main_group == "H01L 21/02 - Manufacture or treatment of semiconductor devices"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_legacy_epo_string() -> None:
|
||||
assert extract_ipc_symbol("C 07C 405/00 A") == "C07C 405/00"
|
||||
assert extract_ipc_symbol("C 07D 317/20 B") == "C07D 317/20"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_from_legacy_epo_string() -> None:
|
||||
keys = parse_ipc_symbol("C 07D 319/06 B")
|
||||
assert keys.symbol == "C07D 319/06"
|
||||
assert keys.section == "C"
|
||||
assert keys.subclass == "C07D"
|
||||
assert keys.main_group == "C07D319/06"
|
||||
|
||||
|
||||
def test_build_ipc_classification_uses_subgroup_when_only_subgroup_indexed() -> None:
|
||||
keys = parse_ipc_symbol("G02B 6/42")
|
||||
names = {
|
||||
"section": {"G": "PHYSICS"},
|
||||
"class": {"G02B": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS"},
|
||||
"group": {},
|
||||
"subgroup": {
|
||||
"G02B6/42": "Coupling light guides with opto-electronic elements",
|
||||
},
|
||||
}
|
||||
|
||||
result = build_ipc_classification(keys, names)
|
||||
|
||||
assert result.main_group is None
|
||||
assert result.subgroup == (
|
||||
"G02B 6/42 - Coupling light guides with opto-electronic elements"
|
||||
)
|
||||
|
||||
|
||||
def test_build_ipc_classification_omits_levels_without_index_names() -> None:
|
||||
keys = parse_ipc_symbol("G02B 6/44")
|
||||
result = build_ipc_classification(keys, {})
|
||||
|
||||
assert result.symbol == "G02B 6/44"
|
||||
assert result.section is None
|
||||
assert result.main_group is None
|
||||
assert result.subgroup is None
|
||||
|
||||
|
||||
def test_build_ipc_classification_falls_back_to_symbol_only() -> None:
|
||||
keys = parse_ipc_symbol("INVALID")
|
||||
result = build_ipc_classification(keys, {})
|
||||
|
||||
assert result == IpcClassification(symbol="INVALID")
|
||||
@@ -0,0 +1,50 @@
|
||||
import pytest
|
||||
|
||||
from inse.patents import model
|
||||
|
||||
|
||||
def test_patent_entry_keeps_raw_ipc_and_separate_descriptions() -> None:
|
||||
entry = model.PatentEntry(
|
||||
patent_id="US123456",
|
||||
source="USPTO",
|
||||
ipc=["H01L 21/02 20100101AFI20140127BHEP"],
|
||||
ipc_descriptions=[
|
||||
model.IpcClassification(
|
||||
symbol="H01L 21/02",
|
||||
section="H - ELECTRICITY",
|
||||
subclass="H01L - SEMICONDUCTOR DEVICES",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
assert entry.ipc == ["H01L 21/02 20100101AFI20140127BHEP"]
|
||||
assert len(entry.ipc_descriptions) == 1
|
||||
assert entry.ipc_descriptions[0].symbol == "H01L 21/02"
|
||||
|
||||
|
||||
def test_patent_entry_ipc_defaults_to_empty_lists() -> None:
|
||||
entry = model.PatentEntry(patent_id="EP1", source="EPO")
|
||||
|
||||
assert entry.ipc == []
|
||||
assert entry.ipc_descriptions == []
|
||||
assert entry.cpc == []
|
||||
assert entry.cpc_descriptions == []
|
||||
|
||||
|
||||
def test_patent_entry_keeps_raw_cpc_and_separate_descriptions() -> None:
|
||||
entry = model.PatentEntry(
|
||||
patent_id="US123456",
|
||||
source="USPTO",
|
||||
cpc=["A61B 5/0713 20130101AFI20140127BHEP"],
|
||||
cpc_descriptions=[
|
||||
model.IpcClassification(
|
||||
symbol="A61B 5/0713",
|
||||
section="A - HUMAN NECESSITIES",
|
||||
subclass="A61B - DIAGNOSIS",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
assert entry.cpc == ["A61B 5/0713 20130101AFI20140127BHEP"]
|
||||
assert len(entry.cpc_descriptions) == 1
|
||||
assert entry.cpc_descriptions[0].symbol == "A61B 5/0713"
|
||||
@@ -0,0 +1,67 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_posts_to_ipc_index():
|
||||
requests: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request.url.path)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = IpcSearchClient(api_key="test-key", transport=transport)
|
||||
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
assert len(requests) >= 1
|
||||
assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests)
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_does_not_crash_for_subclass_codes():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
|
||||
client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler))
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
@@ -0,0 +1,91 @@
|
||||
from inse.patents import logic, model
|
||||
|
||||
|
||||
def _uspto_patent(
|
||||
patent_id: str = "US12508845",
|
||||
publication_date: str = "20251230",
|
||||
application_type: str | None = None,
|
||||
) -> model.PatentEntry:
|
||||
return model.PatentEntry(
|
||||
patent_id=patent_id,
|
||||
source="USPTO",
|
||||
title="Vehicle pneumatic tyre and rubber mixture for a tread",
|
||||
publication_date=publication_date,
|
||||
publication_year="2025",
|
||||
application_type=application_type,
|
||||
)
|
||||
|
||||
|
||||
def _epo_patent(
|
||||
patent_id: str = "EP2867692",
|
||||
publication_date: str = "20180411",
|
||||
kind: str | None = None,
|
||||
) -> model.PatentEntry:
|
||||
return model.PatentEntry(
|
||||
patent_id=patent_id,
|
||||
source="EPO",
|
||||
title="METHOD FOR GENERATING AND USING A MAP",
|
||||
publication_date=publication_date,
|
||||
publication_year="2018",
|
||||
kind=kind,
|
||||
)
|
||||
|
||||
|
||||
def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
||||
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].patent_id == "US12508845"
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
|
||||
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None:
|
||||
first = _uspto_patent()
|
||||
first.abstract = "First abstract"
|
||||
duplicate = _uspto_patent()
|
||||
duplicate.abstract = "Second abstract"
|
||||
|
||||
result = logic._deduplicate_patents([first, duplicate])
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].abstract == "First abstract"
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
|
||||
application = _epo_patent(publication_date="20161005", kind="A1")
|
||||
grant = _epo_patent(publication_date="20180411", kind="B1")
|
||||
|
||||
result = logic._deduplicate_patents([application, grant])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.kind for patent in result] == ["A1", "B1"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() -> None:
|
||||
earlier = _uspto_patent(publication_date="20241230")
|
||||
later = _uspto_patent(publication_date="20251230")
|
||||
|
||||
result = logic._deduplicate_patents([earlier, later])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types() -> None:
|
||||
utility = _uspto_patent(application_type="utility")
|
||||
reissue = _uspto_patent(application_type="reissue")
|
||||
|
||||
result = logic._deduplicate_patents([utility, reissue])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.application_type for patent in result] == ["utility", "reissue"]
|
||||
Reference in New Issue
Block a user