From e9935207ea521ffbf4712bbc3dc7f673777b38bf Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 17 Jun 2026 09:55:01 +0200 Subject: [PATCH] refactor: clean up patents module --- service/src/main/inse/config.py | 8 +- .../src/main/inse/patents/author_profile.py | 186 --------- .../src/main/inse/patents/disambiguation.py | 126 ------ .../inse/patents/elastic_search_client.py | 373 +++++------------- service/src/main/inse/patents/logic.py | 236 ++++++----- service/src/main/inse/patents/model.py | 34 -- service/src/main/inse/patents/pipeline.py | 209 ---------- service/src/main/inse/patents/repository.py | 182 --------- service/src/main/inse/patents/service.py | 59 +-- service/src/main/inse/patents/test_logic.py | 228 ----------- service/src/main/inse/schema.py | 47 +-- webapp/src/app/api/api/patents.service.ts | 45 --- .../person-patents.component.html | 37 +- .../person-patents.component.scss | 58 +-- .../person-patents.component.ts | 109 ++--- 15 files changed, 275 insertions(+), 1662 deletions(-) delete mode 100644 service/src/main/inse/patents/author_profile.py delete mode 100644 service/src/main/inse/patents/disambiguation.py delete mode 100644 service/src/main/inse/patents/pipeline.py delete mode 100644 service/src/main/inse/patents/repository.py delete mode 100644 service/src/main/inse/patents/test_logic.py diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index cbd9597b..32c57cb2 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -42,13 +42,7 @@ 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 llm_api_url: Optional[str] = None diff --git a/service/src/main/inse/patents/author_profile.py b/service/src/main/inse/patents/author_profile.py deleted file mode 100644 index 91819a64..00000000 --- a/service/src/main/inse/patents/author_profile.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/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) - 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 - ] - 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, - ) - - -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_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) diff --git a/service/src/main/inse/patents/disambiguation.py b/service/src/main/inse/patents/disambiguation.py deleted file mode 100644 index 887f103c..00000000 --- a/service/src/main/inse/patents/disambiguation.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/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 - - 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) diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 5fb58366..ead988af 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -3,51 +3,15 @@ """ 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 @@ -74,129 +38,117 @@ class PatentSearchClient: "Content-Type": "application/json", } - 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": _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": { + def epo_query_by_inventor(self, last_name: str, first_name: str | None = None, size: int = 100) -> dict[str, Any]: + """Search EPO index by inventor first AND last name. + EPO stores full name e.g. 'HANDTE, Marcus' in inventors_name_text. + """ + if first_name: + query = { "bool": { - "should": [ - {"term": {"doc_number": doc_number}}, - {"term": {"_id": patent_id}}, - ], - "minimum_should_match": 1, - }, - }, - } - - def uspto_query_by_patent_id(self, patent_id: str) -> dict[str, Any]: - publication_number = patent_id.removeprefix("US") - return { - "size": 1, - "track_total_hits": True, - "_source": _USPTO_SOURCE_FIELDS, - "query": { - "bool": { - "should": [ - {"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", + "must": [ + { + "match": { + "inventors_name_text": { + "query": last_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": { + "inventors_name_text": { + "query": first_name, + "operator": "and", + } + } + }, + ] + } + } + else: + query = { "match": { - text_field: { - "query": variant, + "inventors_name_text": { + "query": last_name, "operator": "and", - }, - }, - }) - - if profile.last_name: - should.append({"term": {keyword_field: profile.last_name}}) + } + } + } return { - "bool": { - "should": should, - "minimum_should_match": 1, - }, + "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", + ], + "query": query, + } + + def uspto_query_by_inventor(self, last_name: str, first_name: str | None = None, size: int = 100) -> dict[str, Any]: + """Search USPTO index by inventor first AND last name. + After Arman's fix, USPTO also stores first name in inventors_names. + """ + if first_name: + query = { + "bool": { + "must": [ + { + "match": { + "inventors_names_text": { + "query": last_name, + "operator": "and", + } + } + }, + { + "match": { + "inventors_names_text": { + "query": first_name, + "operator": "and", + } + } + }, + ] + } + } + else: + query = { + "match": { + "inventors_names_text": { + "query": last_name, + "operator": "and", + } + } + } + + return { + "size": size, + "track_total_hits": True, + "_source": [ + "publication_number", + "country", + "publication_date", + "publication_year", + "title", + "abstract", + "inventors_names", + "inventors_names_text", + "assignees_orgs", + "ipcr", + "ipcr_text", + ], + "query": query, } async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: @@ -205,66 +157,6 @@ 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, @@ -277,57 +169,4 @@ class PatentSearchClient: json=payload, ) response.raise_for_status() - 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 + return response.json() \ No newline at end of file diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index ecd75b2f..ff30648c 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -1,155 +1,147 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - Business logic for patent matching by author. + Business logic for patent matching by author name. """ -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 . 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 +from .elastic_search_client import MissingApiKeyError +from .elastic_search_client import PatentSearchClient logger = logging.getLogger(__name__) async def get_patents_by_author_id( author_id: str, - db: Session, - *, - refresh: bool = False, client: PatentSearchClient | None = None, ) -> model.PatentsByAuthorResponse: - normalized_id = normalize_author_id(author_id) - build_meta = repository.get_build_meta(db, normalized_id) + search_client = client or PatentSearchClient() - 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 = _get_author(author_id) + if not author: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=None, + patent_count=0, + patents=[], + ) - return load_author_patents(db, author_id) + author_name = author.display_name + last_name = _extract_last_name(author_name) + first_name = _extract_first_name(author_name) + if not last_name: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + ) -async def rebuild_patents_for_author( - author_id: str, - db: Session, - *, - client: PatentSearchClient | None = None, -) -> model.PatentsByAuthorResponse: try: - return await rebuild_author_patents(author_id, db, client=client) + epo_data, uspto_data = await _search_both_indices( + search_client, last_name, first_name + ) 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) -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".', - ) + # Group by patent_id and keep one version per patent + grouped: dict[str, model.PatentEntry] = {} + for patent in all_patents: + if patent.patent_id not in grouped: + grouped[patent.patent_id] = patent - normalized_id = normalize_author_id(author_id) - patent: model.PatentEntry | None = None - - 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 - - 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"] - - repository.upsert_override( - db, - normalized_id, - patent_id, - action, - reason=request.reason, - patent=patent, - ) - db.commit() - - return model.PatentOverrideResponse( - author_id=normalized_id, - patent_id=patent_id, - action=action, - reason=request.reason, - patent=patent, + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=len(grouped), + patents=list(grouped.values()), ) -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 +async def _search_both_indices(client, last_name, first_name): + import asyncio + epo_result, uspto_result = await asyncio.gather( + client.search_epo(client.epo_query_by_inventor(last_name, first_name)), + client.search_uspto(client.uspto_query_by_inventor(last_name, first_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 \ No newline at end of file diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index 0246b2d4..31ebc18c 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -1,5 +1,3 @@ -from datetime import datetime - from pydantic import BaseModel, Field @@ -14,41 +12,9 @@ class PatentEntry(BaseModel): assignees: list[str] = Field(default_factory=list) ipc: list[str] = Field(default_factory=list) country: 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] - 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 diff --git a/service/src/main/inse/patents/pipeline.py b/service/src/main/inse/patents/pipeline.py deleted file mode 100644 index ee1d7492..00000000 --- a/service/src/main/inse/patents/pipeline.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/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 diff --git a/service/src/main/inse/patents/repository.py b/service/src/main/inse/patents/repository.py deleted file mode 100644 index 5a049f54..00000000 --- a/service/src/main/inse/patents/repository.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/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 diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 2c41647e..53a27446 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -3,11 +3,7 @@ """ REST API for patent matching by author. """ -from fastapi import APIRouter, Depends, HTTPException, Query -from sqlalchemy.orm import Session -from starlette.status import HTTP_404_NOT_FOUND - -from .. import database +from fastapi import APIRouter from . import logic from . import model @@ -18,54 +14,7 @@ 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.", + summary="Get patents matched to an author by name.", ) -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.") +async def get_patents_by_author(author_id: str): + return await logic.get_patents_by_author_id(author_id) diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py deleted file mode 100644 index 49a15ac1..00000000 --- a/service/src/main/inse/patents/test_logic.py +++ /dev/null @@ -1,228 +0,0 @@ -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" diff --git a/service/src/main/inse/schema.py b/service/src/main/inse/schema.py index b1b59c1b..d03a1b33 100644 --- a/service/src/main/inse/schema.py +++ b/service/src/main/inse/schema.py @@ -4,9 +4,7 @@ This module defines the schema for the database used by the service using sql alchemy. """ -from datetime import datetime - -from sqlalchemy import DateTime, String, Text, UniqueConstraint +from sqlalchemy import String from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column @@ -24,46 +22,3 @@ 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) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index ab42b885..6a0e0b8a 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -33,20 +33,7 @@ export interface PatentEntry { ipc: string[]; country: 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 { @@ -54,16 +41,12 @@ export interface PatentsByAuthorResponse { author_name: string | null; patent_count: number; patents: PatentEntry[]; - from_cache?: boolean; - last_built_at?: string | null; - search_meta?: PatentSearchMeta | null; } type GetPatentsByAuthorOptions = { httpHeaderAccept?: 'application/json'; context?: HttpContext; transferCache?: boolean; - refresh?: boolean; }; @Injectable({ @@ -155,18 +138,12 @@ 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( 'get', `${basePath}${localVarPath}`, { context: localVarHttpContext, - params: localVarQueryParameters, responseType: responseType_, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, @@ -178,26 +155,4 @@ export class PatentsService extends BaseService { }, ); } - - public rebuildPatentsByAuthor(authorId: string): Observable { - 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( - `${basePath}${localVarPath}`, - null, - { - ...(withCredentials ? { withCredentials } : {}), - headers: this.defaultHeaders, - }, - ); - } } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 841c1ba1..03370197 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -20,29 +20,23 @@ {{ getUsptoCount() }} USPTO

-
-
+
+ +
-
- Relevanz - {{ selectedPatent.confidence_score }} -
- @if (selectedPatent.match_signals?.length) { -
-

Zuordnungs-Signale

-
    - @for (signal of selectedPatent.match_signals; track signal) { -
  • {{ formatSignal(signal) }}
  • - } -
-
- } - @if (selectedPatent.abstract) {

Abstract

diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 079fffd7..9f511648 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -14,8 +14,6 @@ margin-bottom: 8px; display: flex; gap: 24px; - align-items: center; - flex-wrap: wrap; .summary-line { margin: 0; @@ -23,22 +21,6 @@ color: #333; } - .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; } @@ -50,33 +32,35 @@ } .filter-bar { - display: flex; + display: inline-flex; align-items: center; - gap: 8px; - flex-wrap: wrap; + gap: 6px; + width: fit-content; + padding: 10px 14px; + border-radius: 20px; + background: #f2f2f2; + color: #333; + font-size: 14px; span { - font-weight: 500; color: #555; } button { - padding: 6px 14px; - border: 1px solid #ccc; - border-radius: 20px; - background: white; + border: 0; + background: transparent; + color: #111827; + font: inherit; cursor: pointer; - font-size: 14px; - - &:hover { - background: #f0f0f0; - } + outline: none; &.active { - background: #f0f6ff; - color: #0b63ce; - border-color: #bdd4ff; font-weight: 600; + color: #0b63ce; + } + + &:hover { + text-decoration: underline; } } } @@ -281,12 +265,6 @@ color: #1e40af; font-size: 0.8rem; line-height: 1.3; - - &--signal { - background: #eef7ee; - border-color: #cfe6cf; - color: #2f6b2f; - } } .pagination { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index f96dcb14..507f1e88 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,26 +1,11 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { - PatentsService, - PatentEntry, - PatentSearchMeta, -} from '../../api/api/patents.service'; +import { PatentsService, PatentEntry } from '../../api/api/patents.service'; -type SortMode = 'score' | 'date' | 'title'; +type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; -const SIGNAL_LABELS: Record = { - full_name_match: 'Vollständiger Name', - last_name_match: 'Nachname', - first_name_match: 'Vorname', - institution_match: 'Institution', - topic_match: 'Forschungsthema', - coauthor_match: 'Ko-Autor', - publication_topic_match: 'Publikations-Thema', - manual_include: 'Manuell hinzugefügt', -}; - @Component({ selector: 'app-person-patents', imports: [CommonModule], @@ -36,22 +21,19 @@ export class PersonPatentsComponent implements OnInit { filteredPatents: PatentEntry[] = []; authorName: string | null = null; selectedPatent: PatentEntry | null = null; - searchMeta: PatentSearchMeta | null = null; loading = true; - rebuilding = false; error = false; - authorId = ''; activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'score'; + sortMode: SortMode = 'date'; selectedPage = 1; readonly pageSize = 10; ngOnInit(): void { this.route.parent?.paramMap.subscribe((params) => { - this.authorId = params.get('id') ?? ''; + const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); @@ -63,51 +45,23 @@ export class PersonPatentsComponent implements OnInit { this.sortMode = sortFromUrl; } - if (this.authorId) { - this.loadPatents(); + 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; + }, + }); } }); } - 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; @@ -127,22 +81,6 @@ 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; - search_meta?: PatentSearchMeta | null; - }): void { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.searchMeta = result.search_meta ?? null; - this.applyFilter(); - this.loading = false; - } - private applyFilter(): void { let patents = this.patents; @@ -155,13 +93,14 @@ export class PersonPatentsComponent implements OnInit { private sortPatents(patents: PatentEntry[]): PatentEntry[] { return [...patents].sort((a, b) => { - if (this.sortMode === 'score') { - return b.confidence_score - a.confidence_score; - } if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare(a.publication_date ?? ''); + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' }); + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); }); } @@ -182,7 +121,7 @@ export class PersonPatentsComponent implements OnInit { } private isValidSortMode(value: string | null): value is SortMode { - return value === 'score' || value === 'date' || value === 'title'; + return value === 'date' || value === 'title'; } getPagedPatents(): PatentEntry[] {