diff --git a/service/src/main/inse/patents/authors/ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py index 957caa8e..11619c3e 100644 --- a/service/src/main/inse/patents/authors/ipc_openalex_mapping.py +++ b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py @@ -27,6 +27,70 @@ SUBCLASS_TOPIC_OVERRIDES: dict[str, str] = { "G01N": "Analytical Methods in Pharmaceuticals", } +_TOPIC_LABEL_STOPWORDS = frozenset({ + "and", + "the", + "for", + "of", + "in", + "with", + "their", + "from", + "into", + "via", + "disease", + "diseases", + "treatment", + "treatments", + "therapy", + "therapies", + "application", + "applications", + "studies", + "study", + "research", + "methods", + "method", + "systems", + "system", + "analysis", + "molecular", + "compounds", + "compound", + "interactions", + "interaction", + "effects", + "properties", + "based", + "related", + "advanced", + "novel", + "using", + "use", + "field", + "fields", + "engineering", + "natural", + "human", + "clinical", + "medical", + "medicine", + "health", + "general", + "other", + "various", + "specific", + "particular", +}) + + +def _meaningful_topic_tokens(label: str) -> set[str]: + return { + token + for token in label.casefold().split() + if len(token) > 3 and token not in _TOPIC_LABEL_STOPWORDS + } + @dataclass(frozen=True) class MappedOpenAlexTopic: @@ -197,6 +261,9 @@ def load_ipc_openalex_mapping() -> dict[str, dict[str, MappedOpenAlexTopic]]: def clear_mapping_cache() -> None: load_ipc_openalex_mapping.cache_clear() _load_topic_cache.cache_clear() + from inse.patents.patents_openalex_keywords.resolver import clear_resolver_caches + + clear_resolver_caches() def _normalize_symbol(symbol: str | None) -> str: @@ -322,7 +389,12 @@ def author_topic_labels(author: Author) -> set[str]: return labels -def _topic_labels_match(mapped: MappedOpenAlexTopic, author: Author) -> bool: +def _topic_labels_match( + mapped: MappedOpenAlexTopic, + author: Author, + *, + strict: bool = False, +) -> bool: mapped_label = (mapped.topic_display_name or "").casefold() if not mapped_label: return False @@ -331,6 +403,15 @@ def _topic_labels_match(mapped: MappedOpenAlexTopic, author: Author) -> bool: if mapped_label in author_labels: return True + if strict: + mapped_tokens = _meaningful_topic_tokens(mapped_label) + if not mapped_tokens: + return False + for label in author_labels: + if len(mapped_tokens & _meaningful_topic_tokens(label)) >= 2: + return True + return False + mapped_tokens = {token for token in mapped_label.split() if len(token) > 2} for label in author_labels: if mapped_label in label or label in mapped_label: @@ -384,22 +465,122 @@ def refs_overlap(left: OpenAlexTopicRefs, right: OpenAlexTopicRefs) -> bool: return False -def patent_topics_match_author( +def strict_refs_overlap(left: OpenAlexTopicRefs, right: OpenAlexTopicRefs) -> bool: + """Topic/subfield overlap only — used for ambiguous inventor names.""" + if left.topic_ids & right.topic_ids: + return True + if left.subfield_ids & right.subfield_ids: + return True + return False + + +def mapped_topics_match_author_strict( + mapped_topics: list[MappedOpenAlexTopic], + author: Author, +) -> bool: + author_refs = author_openalex_topic_refs(author) + if not any((author_refs.topic_ids, author_refs.subfield_ids)): + return True + if not mapped_topics: + return False + return any( + strict_refs_overlap(mapped_topic_refs(mapped), author_refs) + for mapped in mapped_topics + ) + + +def mapped_topics_match_author_for_ambiguous( + patent: model.PatentEntry, + author: Author, + keywords_mapped: list[MappedOpenAlexTopic], + mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, +) -> bool: + """Topic match for same-named inventors without hierarchy/field false positives.""" + from inse.patents.authors.identity import best_name_match_kind + + table = mapping if mapping is not None else load_ipc_openalex_mapping() + legacy_mapped = resolve_mapped_topics_for_patent(patent, table) + + if mapped_topics_match_author_strict(keywords_mapped, author): + return True + if mapped_topics_match_author_strict(legacy_mapped, author): + return True + if any( + _topic_labels_match(mapped, author, strict=True) + for mapped in keywords_mapped + ): + return True + if best_name_match_kind(patent, author.display_name or "") != "full": + return False + return _legacy_primary_field_name_matches_author(patent, author, table) + + +def _primary_legacy_mapped_topics( + patent: model.PatentEntry, + mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, +) -> list[MappedOpenAlexTopic]: + table = mapping if mapping is not None else load_ipc_openalex_mapping() + for raw_code in patent.ipc or []: + mapped = resolve_mapped_topics_for_code(raw_code, table) + if mapped: + return mapped + return [] + + +def _legacy_primary_field_name_matches_author( patent: model.PatentEntry, author: Author, mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, +) -> bool: + if not patent.ipc: + return False + keys = parse_ipc_symbol(extract_ipc_symbol(patent.ipc[0])) + if keys is None: + return False + section = (keys.section or "").upper() + subclass = (keys.subclass or "")[:3].upper() + if section == "B": + return False + if section not in {"A", "C"}: + return False + if section == "C" and subclass not in {"C07", "C12"}: + return False + + primary = _primary_legacy_mapped_topics(patent, mapping) + if not primary: + return False + author_labels = author_topic_labels(author) + return any( + (mapped.field_name or "").casefold() in author_labels + for mapped in primary + if mapped.field_name + ) + + +def mapped_topics_match_author( + mapped_topics: list[MappedOpenAlexTopic], + author: Author, ) -> bool: author_refs = author_openalex_topic_refs(author) if not any((author_refs.topic_ids, author_refs.subfield_ids, author_refs.field_ids)): return True - - mapped_topics = resolve_mapped_topics_for_patent(patent, mapping) if not mapped_topics: return False - return any( refs_overlap(mapped_topic_refs(mapped), author_refs) or _topic_labels_match(mapped, author) or _hierarchy_names_overlap(mapped, author) for mapped in mapped_topics ) + + +def patent_topics_match_author( + patent: model.PatentEntry, + author: Author, + mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, + *, + mapped_topics: list[MappedOpenAlexTopic] | None = None, +) -> bool: + if mapped_topics is None: + mapped_topics = resolve_mapped_topics_for_patent(patent, mapping) + return mapped_topics_match_author(mapped_topics, author) diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index e9109625..8b2df53a 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -11,11 +11,13 @@ from inse.patents.authors.identity import is_ambiguous_name from inse.patents.authors.name_matching import filter_patents_by_author_name from inse.patents.authors.name_variants import parse_person_name from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver from inse.patents.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( deduplicate_patents, enrich_patents_classifications, + expand_matched_epo_application_families, parse_epo_hits, parse_uspto_hits, ) @@ -69,6 +71,16 @@ async def get_patents_by_author_id( all_patents = deduplicate_patents(all_patents) patent_hit_count = len(all_patents) matched_patents = filter_patents_by_author_name(all_patents, author_name) + try: + matched_patents = await expand_matched_epo_application_families( + matched_patents, + search_client, + ) + except Exception: + logger.exception( + "EPO family expansion failed for %s; continuing with name-matched patents only", + author_name, + ) if not matched_patents: return model.PatentsByAuthorResponse( @@ -94,14 +106,25 @@ async def get_patents_by_author_id( openalex_last_name_count=last_name_count, ) + patent_topic_map = None + try: + resolver = PatentOpenAlexMappingResolver() + patent_topic_map = await resolver.resolve_topics_for_patents(matched_patents) + except Exception: + logger.exception( + "OpenAlex topic resolution failed for %s; falling back to legacy mapping", + author_name, + ) + filtered = filter_patents_by_ipc_topic_mapping( matched_patents, author, is_ambiguous=is_ambiguous, + patent_topic_map=patent_topic_map, ) logger.info( - "IPC topic mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter", + "patents_openalex_keywords mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter", author_name, is_ambiguous, len(matched_patents), diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py index 5d6a14c4..af67bf1d 100644 --- a/service/src/main/inse/patents/authors/search_queries.py +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -93,6 +93,48 @@ class InventorSearchQueries: "query": query, } + def epo_query_by_application_number( + self, + application_number: str, + size: int = 20, + ) -> dict[str, Any]: + variants = _application_number_variants(application_number) + if not variants: + return {"size": 0, "query": {"match_none": {}}} + + should = [{"term": {"application_number": variant}} for variant in variants] + query: dict[str, Any] = ( + should[0] + if len(should) == 1 + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": [ + "doc_number", + "country", + "kind", + "date_publication", + "date_publication_year", + "application_number", + "application_filing_date", + "title_en", + "title_de", + "abstract", + "inventors_name", + "applicants_name", + "ipc", + "cpc", + ], + "query": query, + } + def uspto_query_by_inventor( self, display_name: str, @@ -148,3 +190,23 @@ class InventorSearchQueries: ], "query": query, } + + +def _application_number_variants(application_number: str) -> list[str]: + cleaned = application_number.strip() + if not cleaned: + return [] + + seen: set[str] = set() + variants: list[str] = [] + + def _add(value: str) -> None: + value = value.strip() + if value and value not in seen: + seen.add(value) + variants.append(value) + + _add(cleaned) + if cleaned.upper().startswith("EP"): + _add(cleaned[2:]) + return variants diff --git a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py index 9865ae6c..c7a7467f 100644 --- a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py +++ b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py @@ -7,6 +7,7 @@ from inse.patents.authors import ipc_openalex_mapping as mapping_module from inse.patents.authors.ipc_openalex_mapping import ( clear_mapping_cache, load_ipc_openalex_mapping, + mapped_topics_match_author, patent_topics_match_author, resolve_mapped_topics_for_code, ) @@ -145,6 +146,74 @@ def test_filter_rejects_rare_name_on_topic_conflict() -> None: assert filtered == [] +def test_filter_rejects_ambiguous_name_on_fuzzy_label_only_match() -> None: + author = _author_with_topic( + "https://openalex.org/T12345", + "Atherosclerosis and Cardiovascular Diseases", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + tire_patent = model.PatentEntry( + patent_id="US12508845", + source="USPTO", + title="Vehicle pneumatic tyre and rubber mixture for a tread", + ipc=["B60C 1/00"], + inventors=["Christian Weber"], + ) + spurious_cardiac = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T99901", + topic_display_name="Cardiac Valve Diseases and Treatments", + subfield_id="https://openalex.org/subfields/9999", + field_id="https://openalex.org/fields/27", + field_name="Medicine", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [tire_patent], + author, + is_ambiguous=True, + patent_topic_map={"USPTO:US12508845": [spurious_cardiac]}, + ) + assert filtered == [] + + +def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None: + custom = _custom_mapping() + custom["subclass"]["C07K"] = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T10158", + topic_display_name="Cancer Immunotherapy and Biomarkers", + ipc_level="subclass", + ipc_symbol="C07K", + ) + author = _author_with_topic( + "https://openalex.org/T10158", + "Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + patent = model.PatentEntry( + patent_id="EP1555271", + source="EPO", + title="Peptides useful for diagnosis and therapy of TRP-2+ tumors", + ipc=["C07K 14/705"], + inventors=["Schadendorf, Dirk"], + ) + spurious = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + topic_display_name="Antimicrobial Peptides and Activities", + field_name="Medicine", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + mapping=custom, + patent_topic_map={"EPO:EP1555271": [spurious]}, + ) + assert len(filtered) == 1 + + def test_custom_mapping_table() -> None: custom = _custom_mapping() author = Author( diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py index a7d0568a..4ded689c 100644 --- a/service/src/main/inse/patents/authors/topic_filter.py +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -9,12 +9,16 @@ from inse.patents.authors.identity import ( patent_personal_assignee_match, ) from inse.patents.authors.ipc_openalex_mapping import ( + MappedOpenAlexTopic, author_openalex_topic_refs, load_ipc_openalex_mapping, + mapped_topics_match_author, + mapped_topics_match_author_for_ambiguous, patent_topics_match_author, resolve_mapped_topics_for_patent, ) from inse.patents.common import model +from inse.patents.common.parsing import patent_map_key @dataclass(frozen=True) @@ -32,22 +36,30 @@ def _author_has_topic_profile(author: Author) -> bool: def _patent_has_mapped_topics( - patent: model.PatentEntry, - mapping, + mapped_topics: list[MappedOpenAlexTopic], ) -> bool: - return bool(resolve_mapped_topics_for_patent(patent, mapping)) + return bool(mapped_topics) def _topic_conflict( - patent: model.PatentEntry, + mapped_topics: list[MappedOpenAlexTopic], author: Author, - mapping, ) -> bool: if not _author_has_topic_profile(author): return False - if not _patent_has_mapped_topics(patent, mapping): + if not _patent_has_mapped_topics(mapped_topics): return False - return not patent_topics_match_author(patent, author, mapping) + return not mapped_topics_match_author(mapped_topics, author) + + +def _resolve_patent_topics( + patent: model.PatentEntry, + mapping, + patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None, +) -> list[MappedOpenAlexTopic]: + if patent_topic_map is not None: + return patent_topic_map.get(patent_map_key(patent), []) + return resolve_mapped_topics_for_patent(patent, mapping) def filter_patents_by_ipc_topic_mapping( @@ -56,6 +68,7 @@ def filter_patents_by_ipc_topic_mapping( *, is_ambiguous: bool = False, mapping=None, + patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None = None, ) -> list[TopicFilterResult]: table = mapping if mapping is not None else load_ipc_openalex_mapping() institution_names = [ @@ -75,8 +88,18 @@ def filter_patents_by_ipc_topic_mapping( institution_match = patent_institution_match(patent, institution_names) personal_assignee_match = patent_personal_assignee_match(patent, display_name) strong_identity = institution_match or personal_assignee_match - mapped_topics = resolve_mapped_topics_for_patent(patent, table) - matched_via_mapping = patent_topics_match_author(patent, author, table) + mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map) + if is_ambiguous: + matched_via_mapping = mapped_topics_match_author_for_ambiguous( + patent, + author, + mapped_topics, + table, + ) + elif patent_topic_map is not None: + matched_via_mapping = mapped_topics_match_author(mapped_topics, author) + else: + matched_via_mapping = patent_topics_match_author(patent, author, table) if strong_identity: filtered.append( @@ -103,7 +126,7 @@ def filter_patents_by_ipc_topic_mapping( ) continue - if _topic_conflict(patent, author, table): + if _topic_conflict(mapped_topics, author): continue filtered.append( diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py index ce4fea7e..bfb0225d 100644 --- a/service/src/main/inse/patents/common/parsing.py +++ b/service/src/main/inse/patents/common/parsing.py @@ -1,4 +1,5 @@ """Shared patent hit parsing, deduplication, and classification enrichment.""" +import asyncio import logging import httpx @@ -98,6 +99,67 @@ def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: ) +def patent_map_key(patent: model.PatentEntry) -> str: + source, patent_id, publication_date, stage = patent_dedup_key(patent) + return f"{source}:{patent_id}:{publication_date}:{stage}" + + +async def expand_matched_epo_application_families( + matched_patents: list[model.PatentEntry], + search_client, +) -> list[model.PatentEntry]: + """Include other EPO publication stages for already matched applications. + + EPO patents are often published multiple times (e.g. A1 application, later B1 + grant). Inventor nested search may only return one stage, so once a publication + is matched to an author we fetch sibling publications by application number. + """ + application_numbers = sorted( + { + patent.application_number.strip() + for patent in matched_patents + if patent.source == "EPO" + and patent.application_number + and patent.application_number.strip() + } + ) + if not application_numbers: + return matched_patents + + existing_keys = {patent_dedup_key(patent) for patent in matched_patents} + extra: list[model.PatentEntry] = [] + + async def _fetch_family(application_number: str) -> list[model.PatentEntry]: + try: + data = await search_client.search_epo( + search_client.epo_query_by_application_number(application_number) + ) + except (MissingApiKeyError, httpx.HTTPError) as exc: + logger.warning( + "EPO family expansion failed for application %s: %s", + application_number, + exc, + ) + return [] + return parse_epo_hits(data) + + family_results = await asyncio.gather( + *(_fetch_family(application_number) for application_number in application_numbers) + ) + for family_patents in family_results: + for patent in family_patents: + key = patent_dedup_key(patent) + if key in existing_keys: + continue + existing_keys.add(key) + extra.append(patent) + + if not extra: + return matched_patents + + return deduplicate_patents(matched_patents + extra) + + async def enrich_patents_classifications( patents: list[model.PatentEntry], ipc_client: IpcSearchClient, diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py index 613e2706..d9225534 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -14,6 +14,13 @@ def anyio_backend(): return "asyncio" +def test_patent_search_client_exposes_inventor_queries(): + client = PatentSearchClient(api_key="test-key") + assert hasattr(client, "epo_query_by_inventor") + assert hasattr(client, "uspto_query_by_inventor") + assert hasattr(client, "epo_query_by_application_number") + + def test_epo_query_uses_nested_search_and_name_variants(): client = PatentSearchClient(api_key="test-key") payload = client.epo_query_by_inventor("Pedro José Marrón") @@ -31,6 +38,14 @@ def test_uspto_index_is_3_0(): assert ESIndex.EPO_INDEX == "epo_index_1.0" +def test_epo_query_by_application_number_uses_term_filter(): + client = PatentSearchClient(api_key="test-key") + payload = client.epo_query_by_application_number("12743403.3") + + assert payload["query"] == {"term": {"application_number": "12743403.3"}} + assert "application_number" in payload["_source"] + + def test_epo_query_by_applicant_uses_applicants_name_field(): client = PatentSearchClient(api_key="test-key") payload = client.epo_query_by_applicant( @@ -70,4 +85,4 @@ async def test_search_epo_posts_to_correct_index(): await client.search_epo(client.epo_query_by_inventor("Christian Weber")) assert len(captured) == 1 - assert captured[0]["index"] == ESIndex.EPO_INDEX \ No newline at end of file + assert captured[0]["index"] == ESIndex.EPO_INDEX diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py index 5e60288d..9e5f8744 100644 --- a/service/src/main/inse/patents/test_logic.py +++ b/service/src/main/inse/patents/test_logic.py @@ -1,5 +1,8 @@ from inse.patents import model -from inse.patents.common.parsing import deduplicate_patents +from inse.patents.common.parsing import ( + deduplicate_patents, + expand_matched_epo_application_families, +) from inse.patents.institutions.logic import filter_patents_by_institution @@ -93,6 +96,71 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types assert [patent.application_type for patent in result] == ["utility", "reissue"] +def test_expand_matched_epo_application_families_adds_grant_stage() -> None: + application = _epo_patent( + publication_date="20150506", + kind="A1", + ) + application.application_number = "12743403.3" + application.inventors = ["MARRÓN, Pedro José"] + + grant = _epo_patent( + publication_date="20180411", + kind="B1", + ) + grant.application_number = "12743403.3" + grant.inventors = ["HANDTE, Marcus"] + + class _FakeSearchClient: + async def search_epo(self, payload): + return { + "hits": { + "hits": [ + { + "_id": "2867692", + "_source": { + "doc_number": "2867692", + "kind": "A1", + "date_publication": "20150506", + "date_publication_year": 2015, + "application_number": "12743403.3", + "title_en": "METHOD FOR GENERATING AND USING A MAP", + "inventors_name": ["MARRÓN, Pedro José"], + "applicants_name": ["Universität Duisburg-Essen"], + "ipc": ["G01S 5/02"], + }, + }, + { + "_id": "2867692", + "_source": { + "doc_number": "2867692", + "kind": "B1", + "date_publication": "20180411", + "date_publication_year": 2018, + "application_number": "12743403.3", + "title_en": "METHOD FOR GENERATING AND USING A MAP", + "inventors_name": ["HANDTE, Marcus"], + "applicants_name": ["Universität Duisburg-Essen"], + "ipc": ["G01S 5/02"], + }, + }, + ] + } + } + + def epo_query_by_application_number(self, application_number: str): + return {"query": {"term": {"application_number": application_number}}} + + import asyncio + + expanded = asyncio.run( + expand_matched_epo_application_families([application], _FakeSearchClient()) + ) + + assert len(expanded) == 2 + assert {patent.kind for patent in expanded} == {"A1", "B1"} + + def test_assignee_matches_institution_name_accepts_alternative_names() -> None: from inse.patents.name_matching import assignee_matches_institution_name