feat: improve patent matching with disambiguation pipeline and caching
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
This commit is contained in:
@@ -42,6 +42,12 @@ class Settings(BaseSettings):
|
||||
# Patent elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: str = ""
|
||||
patent_es_page_size: int = 500
|
||||
patent_es_max_pages: int = 20
|
||||
patent_disambiguation_min_score_full_name: int = 6
|
||||
patent_disambiguation_min_score_partial: int = 8
|
||||
patent_link_cache_ttl_hours: int = 168
|
||||
patent_publication_context_max_pages: int = 10
|
||||
|
||||
|
||||
# LLM config
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Build author search profiles and publication context for patent disambiguation.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .. import config
|
||||
from ..models.author import Author
|
||||
from ..works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_NAME_PREFIXES = frozenset({
|
||||
"dr", "prof", "mr", "mrs", "ms", "dipl", "ing", "med",
|
||||
})
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuthorProfile:
|
||||
author_id: str
|
||||
display_name: str
|
||||
first_name: str | None
|
||||
last_name: str | None
|
||||
name_variants: list[str] = field(default_factory=list)
|
||||
institutions: list[str] = field(default_factory=list)
|
||||
topics: list[str] = field(default_factory=list)
|
||||
orcid: str | None = None
|
||||
coauthor_last_names: set[str] = field(default_factory=set)
|
||||
publication_keywords: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
def normalize_author_id(author_id: str) -> str:
|
||||
short_id = author_id.strip().removeprefix("https://openalex.org/")
|
||||
return f"https://openalex.org/{short_id}"
|
||||
|
||||
|
||||
def build_author_profile(author: Author, author_id: str) -> AuthorProfile:
|
||||
display_name = author.display_name or ""
|
||||
first_name, last_name = extract_name_parts(display_name)
|
||||
institutions = _extract_institutions(author)
|
||||
topics = [
|
||||
topic.display_name
|
||||
for topic in (author.topics or [])
|
||||
if topic and topic.display_name
|
||||
]
|
||||
orcid = _extract_orcid(author)
|
||||
variants = _build_name_variants(first_name, last_name, display_name)
|
||||
|
||||
return AuthorProfile(
|
||||
author_id=normalize_author_id(author_id),
|
||||
display_name=display_name,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
name_variants=variants,
|
||||
institutions=institutions,
|
||||
topics=topics,
|
||||
orcid=orcid,
|
||||
)
|
||||
|
||||
|
||||
async def enrich_with_publication_context(
|
||||
profile: AuthorProfile,
|
||||
works_client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> AuthorProfile:
|
||||
client = works_client or OpenAlexWorksSearchClient()
|
||||
settings = config.settings
|
||||
page = 1
|
||||
page_size = 100
|
||||
max_pages = settings.patent_publication_context_max_pages
|
||||
normalized_id = profile.author_id
|
||||
|
||||
try:
|
||||
while page <= max_pages:
|
||||
data = await client.search_author_works(
|
||||
normalized_id.removeprefix("https://openalex.org/"),
|
||||
page,
|
||||
page_size,
|
||||
)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
total = data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
_collect_coauthors(source, normalized_id, profile.coauthor_last_names)
|
||||
_collect_publication_keywords(source, profile.publication_keywords)
|
||||
|
||||
if not hits or page * page_size >= total:
|
||||
break
|
||||
page += 1
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Publication context unavailable for author %s: %s",
|
||||
profile.author_id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return profile
|
||||
|
||||
|
||||
def extract_name_parts(display_name: str | None) -> tuple[str | None, str | None]:
|
||||
if not display_name:
|
||||
return None, None
|
||||
|
||||
parts = [
|
||||
part
|
||||
for part in display_name.strip().split()
|
||||
if part.lower().rstrip(".") not in _NAME_PREFIXES
|
||||
]
|
||||
if not parts:
|
||||
return None, None
|
||||
if len(parts) == 1:
|
||||
return None, parts[0]
|
||||
return parts[0], parts[-1]
|
||||
|
||||
|
||||
def _build_name_variants(
|
||||
first_name: str | None,
|
||||
last_name: str | None,
|
||||
display_name: str,
|
||||
) -> list[str]:
|
||||
variants: list[str] = []
|
||||
if display_name.strip():
|
||||
variants.append(display_name.strip())
|
||||
if first_name and last_name:
|
||||
variants.append(f"{first_name} {last_name}")
|
||||
variants.append(f"{last_name}, {first_name}")
|
||||
variants.append(f"{last_name} {first_name}")
|
||||
if len(first_name) > 0:
|
||||
variants.append(f"{first_name[0]}. {last_name}")
|
||||
if last_name:
|
||||
variants.append(last_name)
|
||||
|
||||
seen: set[str] = set()
|
||||
unique: list[str] = []
|
||||
for variant in variants:
|
||||
key = variant.lower()
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
unique.append(variant)
|
||||
return unique
|
||||
|
||||
|
||||
def _collect_coauthors(
|
||||
source: dict,
|
||||
author_id: str,
|
||||
coauthor_last_names: set[str],
|
||||
) -> None:
|
||||
for authorship in source.get("authorships", []):
|
||||
author = authorship.get("author", {})
|
||||
other_id = author.get("id", "")
|
||||
if not other_id or other_id == author_id:
|
||||
continue
|
||||
other_name = author.get("display_name", "")
|
||||
_, last_name = extract_name_parts(other_name)
|
||||
if last_name:
|
||||
coauthor_last_names.add(last_name.lower())
|
||||
|
||||
|
||||
def _collect_publication_keywords(source: dict, keywords: set[str]) -> None:
|
||||
for topic in source.get("topics", []) or []:
|
||||
display_name = topic.get("display_name")
|
||||
if display_name:
|
||||
keywords.add(display_name.lower())
|
||||
|
||||
primary_topic = source.get("primary_topic") or {}
|
||||
display_name = primary_topic.get("display_name")
|
||||
if display_name:
|
||||
keywords.add(display_name.lower())
|
||||
|
||||
for keyword in source.get("keywords", []) or []:
|
||||
display_name = keyword.get("display_name")
|
||||
if display_name:
|
||||
keywords.add(display_name.lower())
|
||||
|
||||
|
||||
def _extract_orcid(author: Author) -> str | None:
|
||||
if author.ids and author.ids.orcid:
|
||||
return str(author.ids.orcid)
|
||||
return str(author.orcid) if author.orcid else None
|
||||
|
||||
|
||||
def _extract_institutions(author: Author) -> list[str]:
|
||||
institutions: set[str] = set()
|
||||
for institution in author.last_known_institutions or []:
|
||||
if institution and institution.display_name:
|
||||
institutions.add(institution.display_name)
|
||||
for affiliation in author.affiliations or []:
|
||||
inst = getattr(affiliation, "institution", None)
|
||||
if inst and getattr(inst, "display_name", None):
|
||||
institutions.add(inst.display_name)
|
||||
return list(institutions)
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Rule-based patent-author disambiguation with publication cross-validation.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from .author_profile import AuthorProfile
|
||||
|
||||
|
||||
@dataclass
|
||||
class DisambiguationResult:
|
||||
score: int
|
||||
signals: list[str]
|
||||
accepted: bool
|
||||
|
||||
|
||||
def disambiguate_patent_group(
|
||||
versions: list[model.PatentEntry],
|
||||
profile: AuthorProfile,
|
||||
) -> model.PatentEntry | None:
|
||||
best: model.PatentEntry | None = None
|
||||
best_result: DisambiguationResult | None = None
|
||||
|
||||
for patent in versions:
|
||||
result = score_patent(patent, profile)
|
||||
if not result.accepted:
|
||||
continue
|
||||
patent.confidence_score = result.score
|
||||
patent.match_signals = result.signals
|
||||
if best is None or result.score > best_result.score: # type: ignore[union-attr]
|
||||
best = patent
|
||||
best_result = result
|
||||
|
||||
return best
|
||||
|
||||
|
||||
def score_patent(
|
||||
patent: model.PatentEntry,
|
||||
profile: AuthorProfile,
|
||||
) -> DisambiguationResult:
|
||||
settings = config.settings
|
||||
signals: list[str] = []
|
||||
score = 0
|
||||
|
||||
inventors_lower = [inventor.lower() for inventor in patent.inventors]
|
||||
title_abstract = ((patent.title or "") + " " + (patent.abstract or "")).lower()
|
||||
|
||||
full_name_match = False
|
||||
if profile.first_name and profile.last_name:
|
||||
full_name_match = any(
|
||||
profile.first_name.lower() in inventor
|
||||
and profile.last_name.lower() in inventor
|
||||
for inventor in inventors_lower
|
||||
)
|
||||
if full_name_match:
|
||||
score += 5
|
||||
signals.append("full_name_match")
|
||||
|
||||
if profile.last_name and any(profile.last_name.lower() in inventor for inventor in inventors_lower):
|
||||
score += 2
|
||||
if "last_name_match" not in signals:
|
||||
signals.append("last_name_match")
|
||||
|
||||
if profile.first_name and any(profile.first_name.lower() in inventor for inventor in inventors_lower):
|
||||
score += 2
|
||||
if "first_name_match" not in signals:
|
||||
signals.append("first_name_match")
|
||||
|
||||
for institution in profile.institutions:
|
||||
institution_words = set(institution.lower().split())
|
||||
for assignee in patent.assignees:
|
||||
assignee_words = set(assignee.lower().split())
|
||||
meaningful = {
|
||||
word for word in (institution_words & assignee_words) if len(word) > 3
|
||||
}
|
||||
if len(meaningful) >= 2:
|
||||
score += 3
|
||||
signals.append("institution_match")
|
||||
break
|
||||
if "institution_match" in signals:
|
||||
break
|
||||
|
||||
if profile.orcid and patent.orcid and profile.orcid.lower() in patent.orcid.lower():
|
||||
score += 5
|
||||
signals.append("orcid_match")
|
||||
|
||||
topic_hits = 0
|
||||
for topic in profile.topics:
|
||||
if topic.lower() in title_abstract:
|
||||
topic_hits += 1
|
||||
score += 1
|
||||
if topic_hits == 1:
|
||||
signals.append("topic_match")
|
||||
if topic_hits >= 3:
|
||||
break
|
||||
|
||||
coauthor_hits = 0
|
||||
for coauthor_last_name in profile.coauthor_last_names:
|
||||
if any(coauthor_last_name in inventor for inventor in inventors_lower):
|
||||
coauthor_hits += 1
|
||||
score += 2
|
||||
if coauthor_hits == 1:
|
||||
signals.append("coauthor_match")
|
||||
if coauthor_hits >= 2:
|
||||
break
|
||||
|
||||
keyword_hits = 0
|
||||
for keyword in profile.publication_keywords:
|
||||
if len(keyword) > 4 and keyword in title_abstract:
|
||||
keyword_hits += 1
|
||||
score += 1
|
||||
if keyword_hits == 1:
|
||||
signals.append("publication_topic_match")
|
||||
if keyword_hits >= 2:
|
||||
break
|
||||
|
||||
threshold = (
|
||||
settings.patent_disambiguation_min_score_full_name
|
||||
if full_name_match
|
||||
else settings.patent_disambiguation_min_score_partial
|
||||
)
|
||||
has_name_signal = "last_name_match" in signals or "full_name_match" in signals
|
||||
accepted = score >= threshold and has_name_signal
|
||||
|
||||
return DisambiguationResult(score=score, signals=signals, accepted=accepted)
|
||||
@@ -3,15 +3,51 @@
|
||||
"""
|
||||
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from .author_profile import AuthorProfile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_2.0"
|
||||
|
||||
_EPO_SOURCE_FIELDS = [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"ipc_text",
|
||||
]
|
||||
|
||||
_USPTO_SOURCE_FIELDS = [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"inventors_names_text",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"ipcr_text",
|
||||
]
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
@@ -38,84 +74,128 @@ class PatentSearchClient:
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def epo_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]:
|
||||
"""Search EPO index by inventor last name."""
|
||||
def epo_query_by_profile(
|
||||
self,
|
||||
profile: AuthorProfile,
|
||||
page: int,
|
||||
size: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"ipc_text",
|
||||
],
|
||||
"_source": _EPO_SOURCE_FIELDS,
|
||||
"query": self._inventor_bool_query(
|
||||
profile,
|
||||
text_field="inventors_name_text",
|
||||
keyword_field="inventors_name",
|
||||
),
|
||||
}
|
||||
|
||||
def uspto_query_by_profile(
|
||||
self,
|
||||
profile: AuthorProfile,
|
||||
page: int,
|
||||
size: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"_source": _USPTO_SOURCE_FIELDS,
|
||||
"query": self._inventor_bool_query(
|
||||
profile,
|
||||
text_field="inventors_names_text",
|
||||
keyword_field="inventors_names",
|
||||
),
|
||||
}
|
||||
|
||||
def epo_query_by_patent_id(self, patent_id: str) -> dict[str, Any]:
|
||||
doc_number = patent_id.removeprefix("EP")
|
||||
return {
|
||||
"size": 1,
|
||||
"track_total_hits": True,
|
||||
"_source": _EPO_SOURCE_FIELDS,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
"inventors_name_text": {
|
||||
"query": last_name,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"inventors_name": last_name
|
||||
}
|
||||
},
|
||||
{"term": {"doc_number": doc_number}},
|
||||
{"term": {"_id": patent_id}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
def uspto_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]:
|
||||
"""Search USPTO index by inventor last name."""
|
||||
def uspto_query_by_patent_id(self, patent_id: str) -> dict[str, Any]:
|
||||
publication_number = patent_id.removeprefix("US")
|
||||
return {
|
||||
"size": size,
|
||||
"size": 1,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"inventors_names_text",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"ipcr_text",
|
||||
],
|
||||
"_source": _USPTO_SOURCE_FIELDS,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
"inventors_names_text": {
|
||||
"query": last_name,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"inventors_names": last_name
|
||||
}
|
||||
},
|
||||
{"term": {"publication_number": publication_number}},
|
||||
{"term": {"_id": patent_id}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _inventor_bool_query(
|
||||
profile: AuthorProfile,
|
||||
*,
|
||||
text_field: str,
|
||||
keyword_field: str,
|
||||
) -> dict[str, Any]:
|
||||
should: list[dict[str, Any]] = []
|
||||
|
||||
if profile.first_name and profile.last_name:
|
||||
full_name = f"{profile.first_name} {profile.last_name}"
|
||||
should.extend([
|
||||
{
|
||||
"match": {
|
||||
text_field: {
|
||||
"query": full_name,
|
||||
"operator": "and",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"match_phrase": {
|
||||
text_field: f"{profile.last_name}, {profile.first_name}",
|
||||
},
|
||||
},
|
||||
{
|
||||
"bool": {
|
||||
"must": [
|
||||
{"term": {keyword_field: profile.last_name}},
|
||||
{"match": {text_field: profile.first_name}},
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
for variant in profile.name_variants:
|
||||
should.append({
|
||||
"match": {
|
||||
text_field: {
|
||||
"query": variant,
|
||||
"operator": "and",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if profile.last_name:
|
||||
should.append({"term": {keyword_field: profile.last_name}})
|
||||
|
||||
return {
|
||||
"bool": {
|
||||
"should": should,
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -125,6 +205,66 @@ class PatentSearchClient:
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
|
||||
async def fetch_all_epo(self, profile: AuthorProfile) -> tuple[int, list[dict[str, Any]]]:
|
||||
return await self._fetch_all_pages(
|
||||
profile,
|
||||
self.epo_query_by_profile,
|
||||
self.search_epo,
|
||||
)
|
||||
|
||||
async def fetch_all_uspto(self, profile: AuthorProfile) -> tuple[int, list[dict[str, Any]]]:
|
||||
return await self._fetch_all_pages(
|
||||
profile,
|
||||
self.uspto_query_by_profile,
|
||||
self.search_uspto,
|
||||
)
|
||||
|
||||
async def lookup_patent(self, patent_id: str) -> model.PatentEntry | None:
|
||||
source = patent_id[:2].upper()
|
||||
if source == "EP":
|
||||
data = await self.search_epo(self.epo_query_by_patent_id(patent_id))
|
||||
patents = parse_epo_hits(data)
|
||||
elif source == "US":
|
||||
data = await self.search_uspto(self.uspto_query_by_patent_id(patent_id))
|
||||
patents = parse_uspto_hits(data)
|
||||
else:
|
||||
return None
|
||||
return patents[0] if patents else None
|
||||
|
||||
async def _fetch_all_pages(
|
||||
self,
|
||||
profile: AuthorProfile,
|
||||
query_builder,
|
||||
search_fn,
|
||||
) -> tuple[int, list[dict[str, Any]]]:
|
||||
settings = config.settings
|
||||
page = 1
|
||||
page_size = settings.patent_es_page_size
|
||||
max_pages = settings.patent_es_max_pages
|
||||
total_hits = 0
|
||||
all_hits: list[dict[str, Any]] = []
|
||||
|
||||
while page <= max_pages:
|
||||
payload = query_builder(profile, page, page_size)
|
||||
data = await search_fn(payload)
|
||||
total_hits = data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
all_hits.extend(hits)
|
||||
|
||||
if not hits or page * page_size >= total_hits:
|
||||
break
|
||||
page += 1
|
||||
|
||||
if page > max_pages and page * page_size < total_hits:
|
||||
logger.warning(
|
||||
"Patent search truncated for author %s at %s pages (total hits: %s).",
|
||||
profile.author_id,
|
||||
max_pages,
|
||||
total_hits,
|
||||
)
|
||||
|
||||
return total_hits, all_hits
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
@@ -137,4 +277,57 @@ class PatentSearchClient:
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return response.json()
|
||||
|
||||
|
||||
def _normalize_str_list(value: Any) -> list[str]:
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, list):
|
||||
return [str(item) for item in value if item is not None and str(item).strip()]
|
||||
return [str(value)] if str(value).strip() else []
|
||||
|
||||
|
||||
def _optional_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def parse_epo_hits(data: dict[str, Any]) -> list[model.PatentEntry]:
|
||||
patents: list[model.PatentEntry] = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{source.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=source.get("title_en") or source.get("title_de"),
|
||||
abstract=source.get("abstract"),
|
||||
publication_date=_optional_str(source.get("date_publication")),
|
||||
publication_year=_optional_str(source.get("date_publication_year")),
|
||||
inventors=_normalize_str_list(source.get("inventors_name")),
|
||||
assignees=_normalize_str_list(source.get("applicants_name")),
|
||||
ipc=_normalize_str_list(source.get("ipc")),
|
||||
country=source.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def parse_uspto_hits(data: dict[str, Any]) -> list[model.PatentEntry]:
|
||||
patents: list[model.PatentEntry] = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{source.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=source.get("title"),
|
||||
abstract=source.get("abstract"),
|
||||
publication_date=_optional_str(source.get("publication_date")),
|
||||
publication_year=_optional_str(source.get("publication_year")),
|
||||
inventors=_normalize_str_list(source.get("inventors_names")),
|
||||
assignees=_normalize_str_list(source.get("assignees_orgs")),
|
||||
ipc=_normalize_str_list(source.get("ipcr")),
|
||||
country=source.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
@@ -1,269 +1,155 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for patent matching by author name.
|
||||
Business logic for patent matching by author.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.author import Author
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from . import repository
|
||||
from .author_profile import normalize_author_id
|
||||
from .elastic_search_client import MissingApiKeyError, PatentSearchClient
|
||||
from .pipeline import rebuild_author_patents, load_author_patents
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MIN_CONFIDENCE_SCORE = 4
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
db: Session,
|
||||
*,
|
||||
refresh: bool = False,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
build_meta = repository.get_build_meta(db, normalized_id)
|
||||
|
||||
author = _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
if refresh or build_meta is None or not repository.is_cache_fresh(build_meta.built_at):
|
||||
try:
|
||||
return await rebuild_author_patents(author_id, db, client=client)
|
||||
except MissingApiKeyError as exc:
|
||||
cached = load_author_patents(db, author_id)
|
||||
if cached.patent_count > 0:
|
||||
return cached
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
cached = load_author_patents(db, author_id)
|
||||
if cached.patent_count > 0:
|
||||
return cached
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
return load_author_patents(db, author_id)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
institutions = _extract_all_institutions(author)
|
||||
topics = _extract_topics(author)
|
||||
orcid = _extract_orcid(author)
|
||||
|
||||
async def rebuild_patents_for_author(
|
||||
author_id: str,
|
||||
db: Session,
|
||||
*,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
try:
|
||||
epo_data, uspto_data = await _search_both_indices(search_client, last_name)
|
||||
return await rebuild_author_patents(author_id, db, client=client)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.") from 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
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
|
||||
# Group by patent_id to check all versions together
|
||||
grouped: dict[str, list[model.PatentEntry]] = defaultdict(list)
|
||||
for patent in all_patents:
|
||||
grouped[patent.patent_id].append(patent)
|
||||
async def set_patent_override(
|
||||
author_id: str,
|
||||
patent_id: str,
|
||||
request: model.PatentOverrideRequest,
|
||||
db: Session,
|
||||
*,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentOverrideResponse:
|
||||
action = request.action.strip().lower()
|
||||
if action not in {"include", "exclude"}:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='action must be "include" or "exclude".',
|
||||
)
|
||||
|
||||
result_patents = []
|
||||
for patent_id, versions in grouped.items():
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
patent: model.PatentEntry | None = None
|
||||
|
||||
# Step 1: Check if first+last name appear together in ONE inventor entry
|
||||
# across any version
|
||||
if first_name and last_name:
|
||||
name_ok = any(
|
||||
first_name.lower() in inv.lower() and last_name.lower() in inv.lower()
|
||||
for version in versions
|
||||
for inv in version.inventors
|
||||
)
|
||||
if not name_ok:
|
||||
continue
|
||||
if action == "include":
|
||||
links = repository.get_links(db, author_id)
|
||||
existing = next(
|
||||
(entry for entry in repository.links_to_patents(links) if entry.patent_id == patent_id),
|
||||
None,
|
||||
)
|
||||
if existing is not None:
|
||||
patent = existing
|
||||
else:
|
||||
search_client = client or PatentSearchClient()
|
||||
try:
|
||||
patent = await search_client.lookup_patent(patent_id)
|
||||
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 lookup failed.",
|
||||
) from exc
|
||||
|
||||
# Step 2: Check institution across ALL versions that have assignees
|
||||
# If ANY version has assignees that don't match our institutions → reject all
|
||||
versions_with_assignees = [v for v in versions if v.assignees]
|
||||
if versions_with_assignees:
|
||||
institution_ok = False
|
||||
for version in versions_with_assignees:
|
||||
for institution in institutions:
|
||||
inst_words = set(institution.lower().split())
|
||||
for asg in version.assignees:
|
||||
asg_words = set(asg.lower().split())
|
||||
meaningful = {w for w in (inst_words & asg_words) if len(w) > 3}
|
||||
if len(meaningful) >= 2:
|
||||
institution_ok = True
|
||||
break
|
||||
if institution_ok:
|
||||
break
|
||||
if institution_ok:
|
||||
break
|
||||
if not institution_ok:
|
||||
continue
|
||||
if patent is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f"Patent {patent_id} was not found in EPO/USPTO indices.",
|
||||
)
|
||||
patent.confidence_score = max(patent.confidence_score, 10)
|
||||
patent.match_signals = ["manual_include"]
|
||||
|
||||
# Step 3: Score all versions, keep best
|
||||
best: model.PatentEntry | None = None
|
||||
for patent in versions:
|
||||
score = _compute_score(patent, first_name, last_name,
|
||||
orcid, institutions, topics)
|
||||
if score >= _MIN_CONFIDENCE_SCORE:
|
||||
patent.confidence_score = score
|
||||
if best is None or score > best.confidence_score:
|
||||
best = patent
|
||||
repository.upsert_override(
|
||||
db,
|
||||
normalized_id,
|
||||
patent_id,
|
||||
action,
|
||||
reason=request.reason,
|
||||
patent=patent,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
if best:
|
||||
result_patents.append(best)
|
||||
|
||||
result_patents.sort(key=lambda p: p.confidence_score, reverse=True)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(result_patents),
|
||||
patents=result_patents,
|
||||
return model.PatentOverrideResponse(
|
||||
author_id=normalized_id,
|
||||
patent_id=patent_id,
|
||||
action=action,
|
||||
reason=request.reason,
|
||||
patent=patent,
|
||||
)
|
||||
|
||||
|
||||
def _compute_score(
|
||||
patent: model.PatentEntry,
|
||||
first_name: str | None,
|
||||
last_name: str | None,
|
||||
orcid: str | None,
|
||||
institutions: list[str],
|
||||
topics: list[str],
|
||||
) -> int:
|
||||
score = 0
|
||||
inventors_lower = [inv.lower() for inv in patent.inventors]
|
||||
title_abstract = ((patent.title or "") + " " + (patent.abstract or "")).lower()
|
||||
|
||||
# Last name match (+2)
|
||||
if last_name and any(last_name.lower() in inv for inv in inventors_lower):
|
||||
score += 2
|
||||
|
||||
# First name match (+2)
|
||||
if first_name and any(first_name.lower() in inv for inv in inventors_lower):
|
||||
score += 2
|
||||
|
||||
# Institution match (+3)
|
||||
for institution in institutions:
|
||||
inst_words = set(institution.lower().split())
|
||||
for asg in patent.assignees:
|
||||
asg_words = set(asg.lower().split())
|
||||
meaningful = {w for w in (inst_words & asg_words) if len(w) > 3}
|
||||
if len(meaningful) >= 2:
|
||||
score += 3
|
||||
break
|
||||
|
||||
# ORCID match (+5)
|
||||
if orcid and getattr(patent, "orcid", None):
|
||||
if orcid.lower() in patent.orcid.lower():
|
||||
score += 5
|
||||
|
||||
# Topics match (+1 each, max +3)
|
||||
topic_score = 0
|
||||
for topic in topics:
|
||||
if topic.lower() in title_abstract:
|
||||
topic_score += 1
|
||||
if topic_score >= 3:
|
||||
break
|
||||
score += topic_score
|
||||
|
||||
return score
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name):
|
||||
import asyncio
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name)),
|
||||
)
|
||||
return epo_result, uspto_result
|
||||
|
||||
|
||||
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=src.get("date_publication"),
|
||||
publication_year=src.get("date_publication_year"),
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=applicants if isinstance(applicants, list) else [applicants],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=src.get("publication_date"),
|
||||
publication_year=src.get("publication_year"),
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=assignees if isinstance(assignees, list) else [assignees],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
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)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
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 _extract_orcid(author: Author) -> str | None:
|
||||
if author.ids and author.ids.orcid:
|
||||
return str(author.ids.orcid)
|
||||
return str(author.orcid) if author.orcid else None
|
||||
|
||||
|
||||
def _extract_all_institutions(author: Author) -> list[str]:
|
||||
institutions: set[str] = set()
|
||||
for inst in (author.last_known_institutions or []):
|
||||
if inst and inst.display_name:
|
||||
institutions.add(inst.display_name)
|
||||
for aff in (author.affiliations or []):
|
||||
inst = getattr(aff, "institution", None)
|
||||
if inst and getattr(inst, "display_name", None):
|
||||
institutions.add(inst.display_name)
|
||||
return list(institutions)
|
||||
|
||||
|
||||
def _extract_topics(author: Author) -> list[str]:
|
||||
return [t.display_name for t in (author.topics or []) if t and t.display_name]
|
||||
def clear_patent_override(
|
||||
author_id: str,
|
||||
patent_id: str,
|
||||
db: Session,
|
||||
) -> bool:
|
||||
deleted = repository.delete_override(db, author_id, patent_id)
|
||||
if deleted:
|
||||
db.commit()
|
||||
return deleted
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
@@ -12,11 +14,42 @@ class PatentEntry(BaseModel):
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
orcid: str | None = None
|
||||
confidence_score: int = 0
|
||||
match_signals: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PatentSearchMeta(BaseModel):
|
||||
epo_total_hits: int = 0
|
||||
uspto_total_hits: int = 0
|
||||
epo_returned_hits: int = 0
|
||||
uspto_returned_hits: int = 0
|
||||
matched_count: int = 0
|
||||
epo_truncated: bool = False
|
||||
uspto_truncated: bool = False
|
||||
coauthor_signals: int = 0
|
||||
publication_keywords: int = 0
|
||||
rebuild_failed: bool = False
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
author_id: str
|
||||
author_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
patents: list[PatentEntry]
|
||||
from_cache: bool = False
|
||||
last_built_at: datetime | None = None
|
||||
search_meta: PatentSearchMeta | None = None
|
||||
|
||||
|
||||
class PatentOverrideRequest(BaseModel):
|
||||
action: str = Field(description='Either "include" or "exclude".')
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
class PatentOverrideResponse(BaseModel):
|
||||
author_id: str
|
||||
patent_id: str
|
||||
action: str
|
||||
reason: str | None = None
|
||||
patent: PatentEntry | None = None
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Disambiguation pipeline: search patents, score matches, persist links.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.author import Author
|
||||
from . import model
|
||||
from .author_profile import (
|
||||
AuthorProfile,
|
||||
build_author_profile,
|
||||
enrich_with_publication_context,
|
||||
normalize_author_id,
|
||||
)
|
||||
from .disambiguation import disambiguate_patent_group
|
||||
from .elastic_search_client import (
|
||||
MissingApiKeyError,
|
||||
PatentSearchClient,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
)
|
||||
from . import repository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def rebuild_author_patents(
|
||||
author_id: str,
|
||||
db: Session,
|
||||
*,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
|
||||
author = _get_author(author_id)
|
||||
if not author:
|
||||
return _empty_response(normalized_id)
|
||||
|
||||
profile = build_author_profile(author, author_id)
|
||||
profile = await enrich_with_publication_context(profile)
|
||||
|
||||
try:
|
||||
epo_total, epo_hits = await search_client.fetch_all_epo(profile)
|
||||
uspto_total, uspto_hits = await search_client.fetch_all_uspto(profile)
|
||||
except MissingApiKeyError:
|
||||
return _response_from_cache_or_empty(
|
||||
db,
|
||||
normalized_id,
|
||||
author.display_name,
|
||||
from_cache=True,
|
||||
rebuild_failed=True,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
logger.error("Patent search failed for author %s: %s", normalized_id, exc)
|
||||
return _response_from_cache_or_empty(
|
||||
db,
|
||||
normalized_id,
|
||||
author.display_name,
|
||||
from_cache=True,
|
||||
rebuild_failed=True,
|
||||
)
|
||||
|
||||
all_patents = (
|
||||
parse_epo_hits({"hits": {"hits": epo_hits}})
|
||||
+ parse_uspto_hits({"hits": {"hits": uspto_hits}})
|
||||
)
|
||||
|
||||
grouped: dict[str, list[model.PatentEntry]] = defaultdict(list)
|
||||
for patent in all_patents:
|
||||
grouped[patent.patent_id].append(patent)
|
||||
|
||||
matched_patents: list[model.PatentEntry] = []
|
||||
for versions in grouped.values():
|
||||
best = disambiguate_patent_group(versions, profile)
|
||||
if best is not None:
|
||||
matched_patents.append(best)
|
||||
|
||||
matched_patents.sort(key=lambda patent: patent.confidence_score, reverse=True)
|
||||
|
||||
search_meta = model.PatentSearchMeta(
|
||||
epo_total_hits=epo_total,
|
||||
uspto_total_hits=uspto_total,
|
||||
epo_returned_hits=len(epo_hits),
|
||||
uspto_returned_hits=len(uspto_hits),
|
||||
matched_count=len(matched_patents),
|
||||
epo_truncated=len(epo_hits) < epo_total,
|
||||
uspto_truncated=len(uspto_hits) < uspto_total,
|
||||
coauthor_signals=len(profile.coauthor_last_names),
|
||||
publication_keywords=len(profile.publication_keywords),
|
||||
)
|
||||
|
||||
built_at = datetime.now(timezone.utc)
|
||||
repository.replace_links(
|
||||
db,
|
||||
normalized_id,
|
||||
matched_patents,
|
||||
author_name=author.display_name,
|
||||
search_meta=search_meta,
|
||||
built_at=built_at,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
return _build_response(
|
||||
db,
|
||||
normalized_id,
|
||||
author.display_name,
|
||||
from_cache=False,
|
||||
built_at=built_at,
|
||||
search_meta=search_meta,
|
||||
)
|
||||
|
||||
|
||||
def load_author_patents(
|
||||
db: Session,
|
||||
author_id: str,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
build_meta = repository.get_build_meta(db, normalized_id)
|
||||
search_meta = None
|
||||
built_at = None
|
||||
author_name = None
|
||||
|
||||
if build_meta is not None:
|
||||
author_name = build_meta.author_name
|
||||
built_at = build_meta.built_at
|
||||
search_meta = model.PatentSearchMeta.model_validate_json(build_meta.search_meta)
|
||||
|
||||
return _build_response(
|
||||
db,
|
||||
normalized_id,
|
||||
author_name,
|
||||
from_cache=True,
|
||||
built_at=built_at,
|
||||
search_meta=search_meta,
|
||||
)
|
||||
|
||||
|
||||
def _build_response(
|
||||
db: Session,
|
||||
author_id: str,
|
||||
author_name: str | None,
|
||||
*,
|
||||
from_cache: bool,
|
||||
built_at: datetime | None,
|
||||
search_meta: model.PatentSearchMeta | None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
links = repository.get_links(db, author_id)
|
||||
patents = repository.apply_overrides(
|
||||
repository.links_to_patents(links),
|
||||
repository.get_overrides(db, author_id),
|
||||
)
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(patents),
|
||||
patents=patents,
|
||||
from_cache=from_cache,
|
||||
last_built_at=built_at,
|
||||
search_meta=search_meta,
|
||||
)
|
||||
|
||||
|
||||
def _response_from_cache_or_empty(
|
||||
db: Session,
|
||||
author_id: str,
|
||||
author_name: str | None,
|
||||
*,
|
||||
from_cache: bool,
|
||||
rebuild_failed: bool,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
links = repository.get_links(db, author_id)
|
||||
if links:
|
||||
return load_author_patents(db, author_id)
|
||||
|
||||
search_meta = model.PatentSearchMeta(rebuild_failed=rebuild_failed) if rebuild_failed else None
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
from_cache=from_cache,
|
||||
search_meta=search_meta,
|
||||
)
|
||||
|
||||
|
||||
def _empty_response(author_id: str) -> model.PatentsByAuthorResponse:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
from_cache=False,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
return result.results[0] if result.results else None
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Persistence layer for author-patent links and manual overrides.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import config
|
||||
from .. import schema
|
||||
from . import model
|
||||
from .author_profile import normalize_author_id
|
||||
|
||||
|
||||
def is_cache_fresh(built_at: datetime | None) -> bool:
|
||||
if built_at is None:
|
||||
return False
|
||||
ttl = timedelta(hours=config.settings.patent_link_cache_ttl_hours)
|
||||
now = datetime.now(timezone.utc)
|
||||
if built_at.tzinfo is None:
|
||||
built_at = built_at.replace(tzinfo=timezone.utc)
|
||||
return now - built_at < ttl
|
||||
|
||||
|
||||
def get_build_meta(db: Session, author_id: str) -> schema.AuthorPatentBuildMeta | None:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
return db.get(schema.AuthorPatentBuildMeta, normalized_id)
|
||||
|
||||
|
||||
def get_links(db: Session, author_id: str) -> list[schema.AuthorPatentLink]:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
return list(
|
||||
db.scalars(
|
||||
select(schema.AuthorPatentLink)
|
||||
.where(schema.AuthorPatentLink.author_id == normalized_id)
|
||||
.order_by(schema.AuthorPatentLink.confidence_score.desc())
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
def get_overrides(db: Session, author_id: str) -> list[schema.AuthorPatentOverride]:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
return list(
|
||||
db.scalars(
|
||||
select(schema.AuthorPatentOverride)
|
||||
.where(schema.AuthorPatentOverride.author_id == normalized_id)
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
def replace_links(
|
||||
db: Session,
|
||||
author_id: str,
|
||||
patents: list[model.PatentEntry],
|
||||
*,
|
||||
author_name: str | None,
|
||||
search_meta: model.PatentSearchMeta,
|
||||
built_at: datetime | None = None,
|
||||
) -> None:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
timestamp = built_at or datetime.now(timezone.utc)
|
||||
|
||||
db.execute(
|
||||
delete(schema.AuthorPatentLink).where(
|
||||
schema.AuthorPatentLink.author_id == normalized_id
|
||||
)
|
||||
)
|
||||
|
||||
for patent in patents:
|
||||
db.add(
|
||||
schema.AuthorPatentLink(
|
||||
author_id=normalized_id,
|
||||
patent_id=patent.patent_id,
|
||||
source=patent.source,
|
||||
confidence_score=patent.confidence_score,
|
||||
match_signals=json.dumps(patent.match_signals),
|
||||
patent_data=patent.model_dump_json(),
|
||||
built_at=timestamp,
|
||||
)
|
||||
)
|
||||
|
||||
existing_meta = db.get(schema.AuthorPatentBuildMeta, normalized_id)
|
||||
if existing_meta is None:
|
||||
existing_meta = schema.AuthorPatentBuildMeta(author_id=normalized_id)
|
||||
db.add(existing_meta)
|
||||
|
||||
existing_meta.author_name = author_name
|
||||
existing_meta.built_at = timestamp
|
||||
existing_meta.search_meta = search_meta.model_dump_json()
|
||||
|
||||
|
||||
def upsert_override(
|
||||
db: Session,
|
||||
author_id: str,
|
||||
patent_id: str,
|
||||
action: str,
|
||||
*,
|
||||
reason: str | None = None,
|
||||
patent: model.PatentEntry | None = None,
|
||||
) -> schema.AuthorPatentOverride:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
existing = db.scalar(
|
||||
select(schema.AuthorPatentOverride).where(
|
||||
schema.AuthorPatentOverride.author_id == normalized_id,
|
||||
schema.AuthorPatentOverride.patent_id == patent_id,
|
||||
)
|
||||
)
|
||||
|
||||
patent_data = patent.model_dump_json() if patent is not None else None
|
||||
if existing is None:
|
||||
existing = schema.AuthorPatentOverride(
|
||||
author_id=normalized_id,
|
||||
patent_id=patent_id,
|
||||
action=action,
|
||||
reason=reason,
|
||||
patent_data=patent_data,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
db.add(existing)
|
||||
return existing
|
||||
|
||||
existing.action = action
|
||||
existing.reason = reason
|
||||
if patent_data is not None:
|
||||
existing.patent_data = patent_data
|
||||
return existing
|
||||
|
||||
|
||||
def delete_override(db: Session, author_id: str, patent_id: str) -> bool:
|
||||
normalized_id = normalize_author_id(author_id)
|
||||
override = db.scalar(
|
||||
select(schema.AuthorPatentOverride).where(
|
||||
schema.AuthorPatentOverride.author_id == normalized_id,
|
||||
schema.AuthorPatentOverride.patent_id == patent_id,
|
||||
)
|
||||
)
|
||||
if override is None:
|
||||
return False
|
||||
db.delete(override)
|
||||
return True
|
||||
|
||||
|
||||
def links_to_patents(links: list[schema.AuthorPatentLink]) -> list[model.PatentEntry]:
|
||||
patents: list[model.PatentEntry] = []
|
||||
for link in links:
|
||||
patent = model.PatentEntry.model_validate_json(link.patent_data)
|
||||
patent.confidence_score = link.confidence_score
|
||||
patent.match_signals = json.loads(link.match_signals or "[]")
|
||||
patents.append(patent)
|
||||
return patents
|
||||
|
||||
|
||||
def apply_overrides(
|
||||
patents: list[model.PatentEntry],
|
||||
overrides: list[schema.AuthorPatentOverride],
|
||||
) -> list[model.PatentEntry]:
|
||||
excluded_ids = {
|
||||
override.patent_id
|
||||
for override in overrides
|
||||
if override.action == "exclude"
|
||||
}
|
||||
result = [patent for patent in patents if patent.patent_id not in excluded_ids]
|
||||
existing_ids = {patent.patent_id for patent in result}
|
||||
|
||||
for override in overrides:
|
||||
if override.action != "include" or override.patent_id in existing_ids:
|
||||
continue
|
||||
if not override.patent_data:
|
||||
continue
|
||||
patent = model.PatentEntry.model_validate_json(override.patent_data)
|
||||
if "manual_include" not in patent.match_signals:
|
||||
patent.match_signals.append("manual_include")
|
||||
result.append(patent)
|
||||
existing_ids.add(patent.patent_id)
|
||||
|
||||
result.sort(key=lambda patent: patent.confidence_score, reverse=True)
|
||||
return result
|
||||
@@ -3,8 +3,11 @@
|
||||
"""
|
||||
REST API for patent matching by author.
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
|
||||
from .. import database
|
||||
from . import logic
|
||||
from . import model
|
||||
|
||||
@@ -15,7 +18,54 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
"/{author_id}/patents",
|
||||
operation_id="getPatentsByAuthor",
|
||||
response_model=model.PatentsByAuthorResponse,
|
||||
summary="Get patents matched to an author by name.",
|
||||
summary="Get patents matched to an author.",
|
||||
)
|
||||
async def get_patents_by_author(author_id: str):
|
||||
return await logic.get_patents_by_author_id(author_id)
|
||||
async def get_patents_by_author(
|
||||
author_id: str,
|
||||
refresh: bool = Query(False, description="Force a rebuild of the patent links."),
|
||||
db: Session = Depends(database.get),
|
||||
):
|
||||
return await logic.get_patents_by_author_id(author_id, db, refresh=refresh)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{author_id}/patents/rebuild",
|
||||
operation_id="rebuildPatentsByAuthor",
|
||||
response_model=model.PatentsByAuthorResponse,
|
||||
summary="Rebuild patent links for an author via the disambiguation pipeline.",
|
||||
)
|
||||
async def rebuild_patents_by_author(
|
||||
author_id: str,
|
||||
db: Session = Depends(database.get),
|
||||
):
|
||||
return await logic.rebuild_patents_for_author(author_id, db)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{author_id}/patents/{patent_id}/override",
|
||||
operation_id="setPatentOverride",
|
||||
response_model=model.PatentOverrideResponse,
|
||||
summary="Manually include or exclude a patent for an author.",
|
||||
)
|
||||
async def set_patent_override(
|
||||
author_id: str,
|
||||
patent_id: str,
|
||||
body: model.PatentOverrideRequest,
|
||||
db: Session = Depends(database.get),
|
||||
):
|
||||
return await logic.set_patent_override(author_id, patent_id, body, db)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{author_id}/patents/{patent_id}/override",
|
||||
operation_id="clearPatentOverride",
|
||||
status_code=204,
|
||||
summary="Remove a manual patent override for an author.",
|
||||
)
|
||||
async def clear_patent_override(
|
||||
author_id: str,
|
||||
patent_id: str,
|
||||
db: Session = Depends(database.get),
|
||||
):
|
||||
if not logic.clear_patent_override(author_id, patent_id, db):
|
||||
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Override not found.")
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from inse import schema
|
||||
from inse.patents import model
|
||||
from inse.patents.author_profile import AuthorProfile, build_author_profile, extract_name_parts
|
||||
from inse.patents.disambiguation import disambiguate_patent_group, score_patent
|
||||
from inse.patents.elastic_search_client import PatentSearchClient, parse_epo_hits, parse_uspto_hits
|
||||
from inse.patents import repository
|
||||
from inse.models.author import Author
|
||||
from inse.models.author_ids import AuthorIds
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
schema.Base.metadata.create_all(engine)
|
||||
session = sessionmaker(bind=engine)()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def _sample_author() -> Author:
|
||||
return Author(
|
||||
id="https://openalex.org/A123",
|
||||
display_name="Max Mustermann",
|
||||
orcid="https://orcid.org/0000-0001-2345-6789",
|
||||
ids=AuthorIds(openalex="https://openalex.org/A123", orcid="https://orcid.org/0000-0001-2345-6789"),
|
||||
last_known_institutions=[
|
||||
DehydratedInstitution(display_name="University of Example"),
|
||||
],
|
||||
topics=[],
|
||||
affiliations=[],
|
||||
)
|
||||
|
||||
|
||||
def test_extract_name_parts_strips_titles():
|
||||
first, last = extract_name_parts("Prof. Dr. Max Mustermann")
|
||||
assert first == "Max"
|
||||
assert last == "Mustermann"
|
||||
|
||||
|
||||
def test_score_patent_accepts_full_name_and_institution():
|
||||
author = _sample_author()
|
||||
profile = build_author_profile(author, "A123")
|
||||
profile.coauthor_last_names.add("schmidt")
|
||||
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP100",
|
||||
source="EPO",
|
||||
title="Machine learning system",
|
||||
inventors=["Max Mustermann", "Anna Schmidt"],
|
||||
assignees=["University of Example Research"],
|
||||
)
|
||||
|
||||
result = score_patent(patent, profile)
|
||||
assert result.accepted is True
|
||||
assert result.score >= 6
|
||||
assert "full_name_match" in result.signals
|
||||
assert "institution_match" in result.signals
|
||||
assert "coauthor_match" in result.signals
|
||||
|
||||
|
||||
def test_disambiguate_patent_group_keeps_best_version():
|
||||
author = _sample_author()
|
||||
profile = build_author_profile(author, "A123")
|
||||
|
||||
weak = model.PatentEntry(
|
||||
patent_id="EP100",
|
||||
source="EPO",
|
||||
inventors=["Mustermann"],
|
||||
assignees=[],
|
||||
)
|
||||
strong = model.PatentEntry(
|
||||
patent_id="EP100",
|
||||
source="EPO",
|
||||
inventors=["Max Mustermann"],
|
||||
assignees=["University of Example"],
|
||||
)
|
||||
|
||||
best = disambiguate_patent_group([weak, strong], profile)
|
||||
assert best is not None
|
||||
assert best.inventors == ["Max Mustermann"]
|
||||
assert best.confidence_score >= 6
|
||||
|
||||
|
||||
def test_repository_apply_overrides_include_and_exclude(db_session):
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
inventors=["Max Mustermann"],
|
||||
confidence_score=8,
|
||||
match_signals=["full_name_match"],
|
||||
)
|
||||
repository.replace_links(
|
||||
db_session,
|
||||
"A123",
|
||||
[patent],
|
||||
author_name="Max Mustermann",
|
||||
search_meta=model.PatentSearchMeta(matched_count=1),
|
||||
)
|
||||
repository.upsert_override(db_session, "A123", "EP1", "exclude")
|
||||
repository.upsert_override(
|
||||
db_session,
|
||||
"A123",
|
||||
"EP2",
|
||||
"include",
|
||||
patent=model.PatentEntry(
|
||||
patent_id="EP2",
|
||||
source="EPO",
|
||||
inventors=["Max Mustermann"],
|
||||
confidence_score=10,
|
||||
match_signals=["manual_include"],
|
||||
),
|
||||
)
|
||||
db_session.commit()
|
||||
|
||||
patents = repository.apply_overrides(
|
||||
repository.links_to_patents(repository.get_links(db_session, "A123")),
|
||||
repository.get_overrides(db_session, "A123"),
|
||||
)
|
||||
patent_ids = {entry.patent_id for entry in patents}
|
||||
assert "EP1" not in patent_ids
|
||||
assert "EP2" in patent_ids
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rebuild_author_patents_persists_links(db_session, monkeypatch):
|
||||
from inse.patents.pipeline import rebuild_author_patents
|
||||
|
||||
author = _sample_author()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.pipeline._get_author",
|
||||
lambda author_id: author,
|
||||
)
|
||||
async def fake_enrich(profile, works_client=None):
|
||||
return profile
|
||||
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.pipeline.enrich_with_publication_context",
|
||||
fake_enrich,
|
||||
)
|
||||
|
||||
class FakeClient:
|
||||
async def fetch_all_epo(self, profile):
|
||||
return 1, [{
|
||||
"_source": {
|
||||
"doc_number": "100",
|
||||
"title_en": "Example patent",
|
||||
"inventors_name": ["Max Mustermann"],
|
||||
"applicants_name": ["University of Example"],
|
||||
},
|
||||
}]
|
||||
|
||||
async def fetch_all_uspto(self, profile):
|
||||
return 0, []
|
||||
|
||||
response = await rebuild_author_patents("A123", db_session, client=FakeClient())
|
||||
assert response.patent_count == 1
|
||||
assert response.patents[0].patent_id == "EP100"
|
||||
assert response.from_cache is False
|
||||
assert response.search_meta is not None
|
||||
assert response.search_meta.matched_count == 1
|
||||
|
||||
cached = repository.get_links(db_session, "A123")
|
||||
assert len(cached) == 1
|
||||
|
||||
|
||||
def test_patent_search_client_builds_full_name_query():
|
||||
profile = AuthorProfile(
|
||||
author_id="https://openalex.org/A123",
|
||||
display_name="Max Mustermann",
|
||||
first_name="Max",
|
||||
last_name="Mustermann",
|
||||
name_variants=["Max Mustermann", "Mustermann, Max"],
|
||||
)
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
query = client.epo_query_by_profile(profile, page=1, size=100)
|
||||
assert query["from"] == 0
|
||||
assert query["size"] == 100
|
||||
should = query["query"]["bool"]["should"]
|
||||
assert any(
|
||||
clause.get("match", {}).get("inventors_name_text", {}).get("query") == "Max Mustermann"
|
||||
for clause in should
|
||||
)
|
||||
|
||||
|
||||
def test_parse_epo_and_uspto_hits():
|
||||
epo = parse_epo_hits({
|
||||
"hits": {
|
||||
"hits": [{
|
||||
"_source": {
|
||||
"doc_number": "123",
|
||||
"title_en": "EPO title",
|
||||
"inventors_name": ["Max Mustermann", None],
|
||||
"date_publication_year": 2015,
|
||||
},
|
||||
}],
|
||||
},
|
||||
})
|
||||
uspto = parse_uspto_hits({
|
||||
"hits": {
|
||||
"hits": [{
|
||||
"_source": {
|
||||
"publication_number": "456",
|
||||
"title": "US title",
|
||||
"inventors_names": ["Max Mustermann"],
|
||||
},
|
||||
}],
|
||||
},
|
||||
})
|
||||
assert epo[0].patent_id == "EP123"
|
||||
assert epo[0].inventors == ["Max Mustermann"]
|
||||
assert epo[0].publication_year == "2015"
|
||||
assert uspto[0].patent_id == "US456"
|
||||
@@ -4,7 +4,9 @@
|
||||
This module defines the schema for the database
|
||||
used by the service using sql alchemy.
|
||||
"""
|
||||
from sqlalchemy import String
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from sqlalchemy.orm import Mapped
|
||||
from sqlalchemy.orm import mapped_column
|
||||
@@ -22,3 +24,46 @@ class Item(Base):
|
||||
description: Mapped[str] = mapped_column(String(2000))
|
||||
def __repr__(self) -> str:
|
||||
return f"Item(id={self.id!r}, name={self.name!r})"
|
||||
|
||||
|
||||
class AuthorPatentLink(Base):
|
||||
"""Persisted author-to-patent match produced by the disambiguation pipeline."""
|
||||
__tablename__ = "author_patent_link"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("author_id", "patent_id", name="uq_author_patent_link"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
author_id: Mapped[str] = mapped_column(String(128), index=True)
|
||||
patent_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
source: Mapped[str] = mapped_column(String(16))
|
||||
confidence_score: Mapped[int] = mapped_column()
|
||||
match_signals: Mapped[str] = mapped_column(Text)
|
||||
patent_data: Mapped[str] = mapped_column(Text)
|
||||
built_at: Mapped[datetime] = mapped_column(DateTime)
|
||||
|
||||
|
||||
class AuthorPatentOverride(Base):
|
||||
"""Manual include/exclude overrides for author-patent links."""
|
||||
__tablename__ = "author_patent_override"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("author_id", "patent_id", name="uq_author_patent_override"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
author_id: Mapped[str] = mapped_column(String(128), index=True)
|
||||
patent_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
action: Mapped[str] = mapped_column(String(16))
|
||||
reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
|
||||
patent_data: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime)
|
||||
|
||||
|
||||
class AuthorPatentBuildMeta(Base):
|
||||
"""Metadata for the last disambiguation run per author."""
|
||||
__tablename__ = "author_patent_build_meta"
|
||||
|
||||
author_id: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
author_name: Mapped[str | None] = mapped_column(String(300), nullable=True)
|
||||
built_at: Mapped[datetime] = mapped_column(DateTime)
|
||||
search_meta: Mapped[str] = mapped_column(Text)
|
||||
|
||||
@@ -32,7 +32,22 @@ export interface PatentEntry {
|
||||
assignees: string[];
|
||||
ipc: string[];
|
||||
country: string | null;
|
||||
orcid?: string | null;
|
||||
confidence_score: number;
|
||||
match_signals?: string[];
|
||||
}
|
||||
|
||||
export interface PatentSearchMeta {
|
||||
epo_total_hits: number;
|
||||
uspto_total_hits: number;
|
||||
epo_returned_hits: number;
|
||||
uspto_returned_hits: number;
|
||||
matched_count: number;
|
||||
epo_truncated: boolean;
|
||||
uspto_truncated: boolean;
|
||||
coauthor_signals: number;
|
||||
publication_keywords: number;
|
||||
rebuild_failed?: boolean;
|
||||
}
|
||||
|
||||
export interface PatentsByAuthorResponse {
|
||||
@@ -40,6 +55,9 @@ export interface PatentsByAuthorResponse {
|
||||
author_name: string | null;
|
||||
patent_count: number;
|
||||
patents: PatentEntry[];
|
||||
from_cache?: boolean;
|
||||
last_built_at?: string | null;
|
||||
search_meta?: PatentSearchMeta | null;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
@@ -99,6 +117,7 @@ export class PatentsService extends BaseService {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
refresh?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
@@ -147,12 +166,18 @@ export class PatentsService extends BaseService {
|
||||
dataFormat: undefined,
|
||||
})}/patents`;
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: new CustomHttpParameterCodec() });
|
||||
if (options?.refresh) {
|
||||
localVarQueryParameters = localVarQueryParameters.set('refresh', 'true');
|
||||
}
|
||||
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
@@ -164,4 +189,26 @@ export class PatentsService extends BaseService {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public rebuildPatentsByAuthor(authorId: string): Observable<PatentsByAuthorResponse> {
|
||||
const localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({
|
||||
name: 'authorId',
|
||||
value: authorId,
|
||||
in: 'path',
|
||||
style: 'simple',
|
||||
explode: false,
|
||||
dataType: 'string',
|
||||
dataFormat: undefined,
|
||||
})}/patents/rebuild`;
|
||||
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.post<PatentsByAuthorResponse>(
|
||||
`${basePath}${localVarPath}`,
|
||||
null,
|
||||
{
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: this.defaultHeaders,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,21 @@
|
||||
<span class="summary-value">{{ getUsptoCount() }}</span>
|
||||
<span class="summary-label"> USPTO</span>
|
||||
</p>
|
||||
@if (fromCache) {
|
||||
<p class="summary-line summary-line--meta">
|
||||
<span class="summary-label">Aus Cache</span>
|
||||
@if (lastBuiltAt) {
|
||||
<span class="summary-label"> · {{ formatDate(lastBuiltAt) }}</span>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
<button
|
||||
class="rebuild-button"
|
||||
type="button"
|
||||
[disabled]="rebuilding"
|
||||
(click)="rebuildPatents()">
|
||||
{{ rebuilding ? 'Aktualisiere...' : 'Neu zuordnen' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="patents-content">
|
||||
@@ -101,6 +116,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (selectedPatent.match_signals?.length) {
|
||||
<div class="detail-section">
|
||||
<h4>Zuordnungs-Signale</h4>
|
||||
<ul class="tag-list tag-list--compact">
|
||||
@for (signal of selectedPatent.match_signals; track signal) {
|
||||
<li class="tag tag--signal">{{ formatSignal(signal) }}</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (selectedPatent.abstract) {
|
||||
<div class="detail-section">
|
||||
<h4>Abstract</h4>
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.summary-line {
|
||||
margin: 0;
|
||||
@@ -21,6 +23,27 @@
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.summary-line--meta {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rebuild-button {
|
||||
margin-left: auto;
|
||||
padding: 8px 14px;
|
||||
border: 1px solid #bdd4ff;
|
||||
border-radius: 20px;
|
||||
background: #f0f6ff;
|
||||
color: #0b63ce;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.summary-label {
|
||||
color: #333;
|
||||
}
|
||||
@@ -263,6 +286,12 @@
|
||||
color: #1e40af;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.3;
|
||||
|
||||
&--signal {
|
||||
background: #eef7ee;
|
||||
border-color: #cfe6cf;
|
||||
color: #2f6b2f;
|
||||
}
|
||||
}
|
||||
|
||||
.pagination {
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { PatentsService, PatentEntry } from '../../api/api/patents.service';
|
||||
import {
|
||||
PatentsService,
|
||||
PatentEntry,
|
||||
PatentSearchMeta,
|
||||
} from '../../api/api/patents.service';
|
||||
|
||||
type SortMode = 'score' | 'date' | 'title';
|
||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||
|
||||
const SIGNAL_LABELS: Record<string, string> = {
|
||||
full_name_match: 'Vollständiger Name',
|
||||
last_name_match: 'Nachname',
|
||||
first_name_match: 'Vorname',
|
||||
institution_match: 'Institution',
|
||||
orcid_match: 'ORCID',
|
||||
topic_match: 'Forschungsthema',
|
||||
coauthor_match: 'Ko-Autor',
|
||||
publication_topic_match: 'Publikations-Thema',
|
||||
manual_include: 'Manuell hinzugefügt',
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-patents',
|
||||
imports: [CommonModule],
|
||||
@@ -21,9 +37,14 @@ export class PersonPatentsComponent implements OnInit {
|
||||
filteredPatents: PatentEntry[] = [];
|
||||
authorName: string | null = null;
|
||||
selectedPatent: PatentEntry | null = null;
|
||||
searchMeta: PatentSearchMeta | null = null;
|
||||
fromCache = false;
|
||||
lastBuiltAt: string | null = null;
|
||||
|
||||
loading = true;
|
||||
rebuilding = false;
|
||||
error = false;
|
||||
authorId = '';
|
||||
|
||||
activeFilter: SourceFilter = 'all';
|
||||
sortMode: SortMode = 'score';
|
||||
@@ -33,7 +54,7 @@ export class PersonPatentsComponent implements OnInit {
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.parent?.paramMap.subscribe((params) => {
|
||||
const authorId = params.get('id') ?? '';
|
||||
this.authorId = params.get('id') ?? '';
|
||||
|
||||
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
|
||||
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
|
||||
@@ -45,23 +66,51 @@ export class PersonPatentsComponent implements OnInit {
|
||||
this.sortMode = sortFromUrl;
|
||||
}
|
||||
|
||||
if (authorId) {
|
||||
this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({
|
||||
next: (result) => {
|
||||
this.patents = result.patents ?? [];
|
||||
this.authorName = result.author_name ?? null;
|
||||
this.applyFilter();
|
||||
this.loading = false;
|
||||
},
|
||||
error: () => {
|
||||
this.error = true;
|
||||
this.loading = false;
|
||||
},
|
||||
});
|
||||
if (this.authorId) {
|
||||
this.loadPatents();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadPatents(refresh = false): void {
|
||||
this.loading = true;
|
||||
this.error = false;
|
||||
|
||||
this.patentsApi
|
||||
.getPatentsByAuthor(this.authorId, 'body', false, {
|
||||
refresh,
|
||||
transferCache: false,
|
||||
})
|
||||
.subscribe({
|
||||
next: (result) => this.applyResult(result),
|
||||
error: () => {
|
||||
this.error = true;
|
||||
this.loading = false;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
rebuildPatents(): void {
|
||||
if (!this.authorId || this.rebuilding) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.rebuilding = true;
|
||||
this.error = false;
|
||||
|
||||
this.patentsApi.rebuildPatentsByAuthor(this.authorId).subscribe({
|
||||
next: (result) => {
|
||||
this.applyResult(result);
|
||||
this.rebuilding = false;
|
||||
},
|
||||
error: () => {
|
||||
this.error = true;
|
||||
this.rebuilding = false;
|
||||
this.loading = false;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setFilter(filter: SourceFilter): void {
|
||||
this.activeFilter = filter;
|
||||
this.selectedPage = 1;
|
||||
@@ -81,6 +130,26 @@ export class PersonPatentsComponent implements OnInit {
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
formatSignal(signal: string): string {
|
||||
return SIGNAL_LABELS[signal] ?? signal;
|
||||
}
|
||||
|
||||
private applyResult(result: {
|
||||
patents?: PatentEntry[];
|
||||
author_name?: string | null;
|
||||
from_cache?: boolean;
|
||||
last_built_at?: string | null;
|
||||
search_meta?: PatentSearchMeta | null;
|
||||
}): void {
|
||||
this.patents = result.patents ?? [];
|
||||
this.authorName = result.author_name ?? null;
|
||||
this.fromCache = result.from_cache ?? false;
|
||||
this.lastBuiltAt = result.last_built_at ?? null;
|
||||
this.searchMeta = result.search_meta ?? null;
|
||||
this.applyFilter();
|
||||
this.loading = false;
|
||||
}
|
||||
|
||||
private applyFilter(): void {
|
||||
let patents = this.patents;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user