diff --git a/service/src/main/inse/patents/authors/filtering.py b/service/src/main/inse/patents/authors/filtering.py new file mode 100644 index 00000000..e2fa0ebe --- /dev/null +++ b/service/src/main/inse/patents/authors/filtering.py @@ -0,0 +1,127 @@ +"""Filter scored patent matches using identity, ambiguity, and conflict rules.""" +from __future__ import annotations + +from inse.patents.authors.name_frequency import score_threshold +from inse.patents.authors.profile import AuthorProfile +from inse.patents.authors.scoring import PatentMatchScore +from inse.patents.common import model + + +def filter_scored_patents( + scored_patents: list[PatentMatchScore], + profile: AuthorProfile, +) -> list[PatentMatchScore]: + threshold = score_threshold(profile.is_single_token) + accepted: list[PatentMatchScore] = [] + + for scored in scored_patents: + if not _passes_filter(scored, profile, threshold): + continue + accepted.append(scored) + + accepted.sort( + key=lambda item: ( + effective_match_score(item, profile), + item.patent.publication_date or "", + ), + reverse=True, + ) + return accepted + + +def effective_match_score(scored: PatentMatchScore, profile: AuthorProfile) -> float: + return max(scored.score, score_threshold(profile.is_single_token)) if _passes_by_identity( + scored, profile + ) else scored.score + + +def effective_match_confidence( + scored: PatentMatchScore, + profile: AuthorProfile, +) -> str: + if scored.confidence != "uncertain": + return scored.confidence + if _passes_by_identity(scored, profile): + return "medium" + return scored.confidence + + +def _passes_by_identity(scored: PatentMatchScore, profile: AuthorProfile) -> bool: + return ( + not profile.is_common_name + and scored.name_match == "full" + and not scored.topic_conflict + and scored.personal_assignee_match + ) + + +def _passes_filter( + scored: PatentMatchScore, + profile: AuthorProfile, + threshold: float, +) -> bool: + if scored.name_match == "none": + return False + + if profile.is_common_name and not scored.has_strong_context: + return False + + if scored.topic_conflict and not (scored.institution_match or scored.co_author_match): + return False + + if _passes_by_identity(scored, profile): + return True + + if scored.score < threshold: + return False + + if scored.confidence == "uncertain": + return False + + return True + + +def to_matched_patent_entry( + scored: PatentMatchScore, + profile: AuthorProfile | None = None, +) -> model.MatchedPatentEntry: + match_score = scored.score + match_confidence = scored.confidence + if profile is not None: + match_score = effective_match_score(scored, profile) + match_confidence = effective_match_confidence(scored, profile) + + if match_confidence == "uncertain": + match_confidence = "medium" + + return model.MatchedPatentEntry( + **scored.patent.model_dump(), + match_score=match_score, + match_confidence=match_confidence, + match_badges=list(scored.badges), + match_reasons=list(scored.reasons), + ) + + +def patent_from_matched(entry: model.MatchedPatentEntry) -> model.PatentEntry: + return model.PatentEntry( + **entry.model_dump( + exclude={ + "match_score", + "match_confidence", + "match_badges", + "match_reasons", + } + ) + ) + + +def disambiguate_patents( + patents: list[model.PatentEntry], + profile: AuthorProfile, +) -> list[model.MatchedPatentEntry]: + from inse.patents.authors.scoring import score_patents + + scored = score_patents(patents, profile) + filtered = filter_scored_patents(scored, profile) + return [to_matched_patent_entry(item, profile) for item in filtered] diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 0dc34be1..55b1c4b4 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -7,13 +7,22 @@ from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE -from inse.patents.authors.name_matching import name_matches +from inse.patents.authors.filtering import disambiguate_patents +from inse.patents.authors.name_matching import name_matches_person, tokens_equal +from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.profile import ( + build_author_profile, + extract_first_name, + extract_last_name, + inventor_last_name, +) 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, parse_epo_hits, + parse_search_total, parse_uspto_hits, ) from inse.patents.ipc_search_client import IpcSearchClient @@ -42,8 +51,9 @@ async def get_patents_by_author_id( ) author_name = author.display_name - last_name = _extract_last_name(author_name) - first_name = _extract_first_name(author_name) + parsed_name = parse_person_name(author_name) + last_name = extract_last_name(author_name) + first_name = extract_first_name(author_name) if not last_name: return model.PatentsByAuthorResponse( @@ -54,9 +64,7 @@ async def get_patents_by_author_id( ) try: - epo_data, uspto_data = await _search_both_indices( - search_client, last_name, first_name - ) + epo_data, uspto_data = await _search_both_indices(search_client, author_name) except MissingApiKeyError as exc: raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, @@ -68,37 +76,68 @@ async def get_patents_by_author_id( detail="Patent search request failed.", ) from exc + patent_hit_count = parse_search_total(epo_data) + parse_search_total(uspto_data) all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - if first_name and last_name: - all_patents = _filter_patents_by_name(all_patents, first_name, last_name) + if parsed_name and parsed_name.is_single_token: + all_patents = _filter_patents_by_last_name(all_patents, last_name) + elif author_name: + all_patents = _filter_patents_by_display_name(all_patents, author_name) all_patents = deduplicate_patents(all_patents) - await enrich_patents_classifications(all_patents, ipc_search_client) + + profile = build_author_profile( + author, + patent_hit_count=patent_hit_count, + ) + matched_patents = disambiguate_patents(all_patents, profile) + + await enrich_patents_classifications( + [patent for patent in matched_patents], + ipc_search_client, + ) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, - patent_count=len(all_patents), - patents=all_patents, + patent_count=len(matched_patents), + is_common_name=profile.is_common_name, + patents=matched_patents, ) -async def _search_both_indices(client, last_name, first_name): +async def _search_both_indices(client, display_name: str): return 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)), + client.search_epo(client.epo_query_by_inventor(display_name)), + client.search_uspto(client.uspto_query_by_inventor(display_name)), ) -def _filter_patents_by_name( +def _filter_patents_by_display_name( + patents: list[model.PatentEntry], + display_name: str, +) -> list[model.PatentEntry]: + return [ + patent + for patent in patents + if any( + name_matches_person(inventor, display_name) + for inventor in patent.inventors + ) + ] + + +def _filter_patents_by_last_name( patents: list[model.PatentEntry], - first_name: str, last_name: str, ) -> list[model.PatentEntry]: return [ - patent for patent in patents - if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors) + patent + for patent in patents + if any( + tokens_equal(inventor_last_name(inventor), last_name, allow_initial=False) + for inventor in patent.inventors + ) ] @@ -106,17 +145,3 @@ 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 diff --git a/service/src/main/inse/patents/authors/name_frequency.py b/service/src/main/inse/patents/authors/name_frequency.py new file mode 100644 index 00000000..eb8df001 --- /dev/null +++ b/service/src/main/inse/patents/authors/name_frequency.py @@ -0,0 +1,124 @@ +"""Heuristics for identifying ambiguous / common author names.""" +from __future__ import annotations + +COMMON_LAST_NAMES: frozenset[str] = frozenset({ + "smith", "johnson", "williams", "brown", "jones", "garcia", "miller", "davis", + "rodriguez", "martinez", "hernandez", "lopez", "gonzalez", "wilson", "anderson", + "thomas", "taylor", "moore", "jackson", "martin", "lee", "perez", "thompson", + "white", "harris", "sanchez", "clark", "ramirez", "lewis", "robinson", "walker", + "young", "allen", "king", "wright", "scott", "torres", "nguyen", "hill", "flores", + "green", "adams", "nelson", "baker", "hall", "rivera", "campbell", "mitchell", + "carter", "roberts", "gomez", "phillips", "evans", "turner", "diaz", "parker", + "cruz", "edwards", "collins", "reyes", "stewart", "morris", "morales", "murphy", + "cook", "rogers", "gutierrez", "ortiz", "morgan", "cooper", "peterson", "bailey", + "reed", "kelly", "howard", "ramos", "kim", "cox", "ward", "richardson", "watson", + "brooks", "sanders", "price", "bennett", "wood", "barnes", "ross", "henderson", + "coleman", "jenkins", "perry", "powell", "long", "patterson", "hughes", "flores", + "washington", "butler", "simmons", "foster", "gonzales", "bryant", "alexander", + "russell", "griffin", "diaz", "hayes", "myers", "ford", "hamilton", "graham", + "sullivan", "wallace", "woods", "cole", "west", "jordan", "owens", "reynolds", + "fisher", "ellis", "harrison", "gibson", "mcdonald", "marshall", "ortiz", + "muller", "mueller", "schmidt", "schneider", "fischer", "weber", "meyer", + "wagner", "becker", "schulz", "hoffmann", "koch", "richter", "klein", "wolf", + "schroder", "neumann", "schwarz", "zimmermann", "braun", "kruger", "hartmann", + "lange", "schmitt", "werner", "schmitz", "krause", "meier", "lehmann", "schmid", + "schulze", "maier", "kohler", "herrmann", "konig", "walter", "mayer", "huber", + "kaiser", "fuchs", "peters", "lang", "scholz", "moller", "weiss", "jung", + "hahn", "schubert", "vogel", "friedrich", "keller", "gunther", "frank", "berger", + "winkler", "roth", "beck", "lorenz", "baumann", "franke", "albrecht", "schuster", + "simon", "ludwig", "bauer", "winter", "kraus", "martin", "schumacher", "krause", + "singh", "kumar", "patel", "sharma", "gupta", "khan", "shah", "reddy", "rao", + "wang", "li", "zhang", "liu", "chen", "yang", "huang", "zhao", "wu", "zhou", + "xu", "sun", "ma", "zhu", "hu", "guo", "he", "gao", "lin", "luo", "zheng", + "tanaka", "sato", "suzuki", "takahashi", "watanabe", "ito", "yamamoto", "nakamura", + "kobayashi", "kato", "yoshida", "yamada", "sasaki", "yamaguchi", "matsumoto", + "inoue", "kimura", "hayashi", "shimizu", "yamazaki", "mori", "abe", "ikeda", + "hashimoto", "ishikawa", "yamashita", "nakajima", "maeda", "fujita", "ogawa", + "goto", "okada", "hasegawa", "murakami", "kondo", "ishii", "saito", "sakamoto", + "martin", "bernard", "dubois", "thomas", "robert", "richard", "petit", "durand", + "leroy", "moreau", "simon", "laurent", "lefebvre", "michel", "garcia", "david", + "bertrand", "roux", "vincent", "fournier", "morel", "girard", "andre", "lefevre", + "mercier", "dupont", "lambert", "bonnet", "francois", "martinez", "legrand", + "garnier", "faure", "rousseau", "blanc", "guerin", "muller", "henry", "roussel", + "nicolas", "perrin", "morin", "mathieu", "gauthier", "robin", "masson", "blanchard", + "giraud", "joly", "riviere", "lucas", "brunet", "gaillard", "barbier", "arnaud", + "martins", "silva", "santos", "oliveira", "souza", "rodrigues", "ferreira", + "alves", "pereira", "lima", "gomes", "costa", "ribeiro", "carvalho", "almeida", + "lopes", "soares", "fernandes", "vieira", "barbosa", "rocha", "dias", "nunes", + "marques", "machado", "mendes", "freitas", "cardoso", "ramos", "teixeira", + "correia", "moreira", "melo", "nascimento", "castro", "pinto", "campos", "araujo", + "rossi", "russo", "ferrari", "esposito", "bianchi", "romano", "ricci", "marino", + "greco", "bruno", "gallo", "conti", "de luca", "mancini", "costa", "giordano", + "rizzo", "lombardi", "moretti", "barbieri", "fontana", "santoro", "mariani", + "rinaldi", "caruso", "ferrara", "galli", "martini", "leone", "longo", "gentile", + "ivanov", "smirnov", "kuznetsov", "popov", "sokolov", "lebedev", "kozlov", + "novikov", "morozov", "petrov", "volkov", "solovyov", "vasiliev", "zaitsev", + "pavlov", "semenov", "golubev", "vinogradov", "bogdanov", "vorobyov", "fyodorov", + "mikhailov", "babeluk", "orlov", "antonov", "nikitin", "fedorov", "yakovlev", + "grigoriev", "romanov", "voronov", "sergeev", "stepanov", "nikolaev", "danilov", + "kowalski", "nowak", "wisniewski", "wojcik", "kowalczyk", "kaminski", "lewandowski", + "zielinski", "szymanski", "wozniak", "dabrowski", "kozlowski", "jankowski", + "mazur", "kwiatkowski", "krawczyk", "piotrowski", "grabowski", "nowakowski", + "pawlowski", "michalski", "nowicki", "adamczyk", "dudek", "zajac", "wieczorek", + "jablonski", "krol", "majewski", "olszewski", "jaworski", "wronski", "malinowski", + "pawlak", "witkowski", "walczak", "stepien", "gorski", "rutkowski", "michalak", + "sikora", "ostrowski", "baran", "duda", "szewczyk", "tomaszewski", "pietrzak", + "marciniak", "wrobel", "zalewski", "jakubowski", "jankowska", "dijk", "de jong", + "bakker", "janssen", "visser", "smit", "de boer", "mulder", "de groot", "bos", + "vos", "peters", "hendriks", "van leeuwen", "dekker", "brouwer", "de wit", + "dijkstra", "smits", "de graaf", "van der meer", "van den berg", "kok", "jacobs", + "vermeulen", "van den broek", "van dam", "schouten", "van de velde", "willems", + "andersson", "johansson", "karlsson", "nilsson", "eriksson", "larsson", "olsson", + "persson", "svensson", "gustafsson", "pettersson", "jonsson", "jansson", "hansson", + "berg", "lindberg", "lindstrom", "lundberg", "jakobsson", "magnusson", "olofsson", + "lindgren", "axelsson", "bergstrom", "lundgren", "mattson", "bergman", "fredriksson", + "hansen", "johansen", "olsen", "larsen", "andersen", "pedersen", "nilsen", "kristiansen", + "jensen", "karlsen", "johnsen", "pettersen", "eriksen", "berg", "haugen", "hagen", + "johannessen", "andreassen", "jacobsen", "dahl", "jorgensen", "halvorsen", "henriksen", + "lund", "sorensen", "jakobsen", "moen", "gundersen", "iversen", "strand", "solberg", + "martinsen", "svendsen", "eide", "knutsen", "berg", "haugland", "ruud", "kristoffersen", +}) + +PATENT_HIT_COUNT_THRESHOLD = 300 + + +def is_single_token_name(display_name: str | None) -> bool: + if not display_name or not display_name.strip(): + return True + return len(display_name.strip().split()) < 2 + + +def is_common_last_name(last_name: str | None) -> bool: + if not last_name: + return False + return normalize_last_name(last_name) in COMMON_LAST_NAMES + + +def normalize_last_name(last_name: str) -> str: + from inse.patents.common.text_normalization import normalize_name_part + + return normalize_name_part(last_name) + + +def is_common_name( + display_name: str | None, + last_name: str | None, + *, + first_name: str | None = None, + patent_hit_count: int | None = None, +) -> bool: + if is_single_token_name(display_name): + return True + if last_name and is_common_last_name(last_name): + return True + # Many raw ES hits are only ambiguous when the first name cannot disambiguate. + if patent_hit_count is not None and patent_hit_count >= PATENT_HIT_COUNT_THRESHOLD: + if not first_name: + return True + if last_name and is_common_last_name(last_name): + return True + return False + + +def score_threshold(is_single_token: bool) -> float: + return 0.8 if is_single_token else 0.6 diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index 369c44ab..39d1a90e 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -1,6 +1,12 @@ """Inventor name normalization and matching.""" import re +from inse.patents.authors.name_variants import ( + ParsedPersonName, + parse_inventor_name, + parse_person_name, + _initials_from_tokens, +) from inse.patents.common.text_normalization import ( name_token_variants, normalize_name_part, @@ -49,7 +55,10 @@ def _initial_tokens_match(left: str | None, right: str | None) -> bool: return False -def _inventor_first_token(inventor_name: str) -> str: +def inventor_first_token(inventor_name: str) -> str: + parsed = parse_inventor_name(inventor_name) + if parsed and parsed.primary_given_name: + return parsed.primary_given_name if "," in inventor_name: _, first_part = [p.strip() for p in inventor_name.split(",", 1)] return first_part.split()[0] if first_part else "" @@ -57,18 +66,109 @@ def _inventor_first_token(inventor_name: str) -> str: return parts[0] if parts else "" +def inventor_search_phrases(display_name: str) -> list[str]: + parsed = parse_person_name(display_name) + if parsed is None: + return [] + + if parsed.is_single_token: + return search_name_variants(parsed.last_name) + + seen: set[str] = set() + phrases: list[str] = [] + + def _add(phrase: str) -> None: + phrase = phrase.strip() + if not phrase: + return + key = phrase.casefold() + if key in seen: + return + seen.add(key) + phrases.append(phrase) + + given_names = list(parsed.given_names) + last_name = parsed.last_name + compound_last = parsed.compound_last_name + full_given = " ".join(given_names) + + _add(f"{full_given} {last_name}") + if compound_last and compound_last != last_name: + _add(f"{full_given} {compound_last}") + + for given_name in given_names: + _add(f"{given_name} {last_name}") + if compound_last and compound_last != last_name: + _add(f"{given_name} {compound_last}") + + initials = _initials_from_tokens(given_names) + if initials: + _add(f"{initials} {last_name}") + if compound_last and compound_last != last_name: + _add(f"{initials} {compound_last}") + dotted = ".".join(char for char in initials) + "." + _add(f"{dotted} {last_name}") + if compound_last and compound_last != last_name: + _add(f"{dotted} {compound_last}") + + _add(f"{last_name}, {full_given}") + for given_name in given_names: + _add(f"{last_name}, {given_name}") + if compound_last and compound_last != last_name: + _add(f"{compound_last}, {full_given}") + + expanded: list[str] = [] + expanded_seen: set[str] = set() + for phrase in phrases: + for variant in search_name_variants(phrase): + key = variant.casefold() + if key in expanded_seen: + continue + expanded_seen.add(key) + expanded.append(variant) + + return expanded + + +def name_matches_person(inventor_name: str, person_display_name: str) -> bool: + author = parse_person_name(person_display_name) + inventor = parse_inventor_name(inventor_name) + if author is None or inventor is None: + return False + + if author.is_single_token: + return _family_name_matches(author, inventor) + + if not _family_name_matches(author, inventor): + return False + return _given_name_matches(author, inventor) + + +def first_name_match_kind_for_person( + inventor_name: str, + person_display_name: str, +) -> str: + if not name_matches_person(inventor_name, person_display_name): + return "none" + if _given_names_full_match( + parse_person_name(person_display_name), + parse_inventor_name(inventor_name), + ): + return "full" + return "initial" + + def first_name_match_kind( inventor_name: str, first_name: str, last_name: str, ) -> str: - if not name_matches(inventor_name, first_name, last_name): - return "none" - - inventor_first = _inventor_first_token(inventor_name) - if tokens_equal(inventor_first, first_name, allow_initial=False): - return "full" - return "initial" + if first_name: + return first_name_match_kind_for_person( + inventor_name, + f"{first_name} {last_name}", + ) + return first_name_match_kind_for_person(inventor_name, last_name) def search_name_variants(value: str | None) -> list[str]: @@ -105,24 +205,74 @@ def search_name_variants(value: str | None) -> list[str]: def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool: if not inventor_name or not last_name: return False + if first_name: + return name_matches_person(inventor_name, f"{first_name} {last_name}") + return name_matches_person(inventor_name, last_name) - name = inventor_name.strip() - if "," in name: - last_part, first_part = [p.strip() for p in name.split(",", 1)] - first_token = first_part.split()[0] if first_part else "" - return ( - tokens_equal(last_part, last_name, allow_initial=False) - and bool(first_name) - and tokens_equal(first_token, first_name) - ) +def _family_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> bool: + author_candidates = _family_name_candidates(author) + inventor_candidates = _family_name_candidates(inventor) + return any( + tokens_equal(author_name, inventor_name, allow_initial=False) + for author_name in author_candidates + for inventor_name in inventor_candidates + ) - parts = name.split() - if len(parts) < 2: + +def _family_name_candidates(parsed: ParsedPersonName) -> set[str]: + candidates = {parsed.last_name} + if parsed.compound_last_name: + candidates.add(parsed.compound_last_name) + return candidates + + +def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> bool: + if not author.given_names: + return True + if not inventor.given_names: return False - return ( - tokens_equal(parts[-1], last_name, allow_initial=False) - and bool(first_name) - and tokens_equal(parts[0], first_name) + primary = author.primary_given_name + if primary and any( + tokens_equal(primary, inventor_given, allow_initial=True) + for inventor_given in inventor.given_names + ): + return True + + return all( + any( + tokens_equal(author_given, inventor_given, allow_initial=True) + for author_given in author.given_names + ) + for inventor_given in inventor.given_names ) + + +def _given_names_full_match( + author: ParsedPersonName | None, + inventor: ParsedPersonName | None, +) -> bool: + if author is None or inventor is None or not author.given_names: + return False + if not inventor.given_names: + return False + + primary = author.primary_given_name + if not primary: + return False + + if not any( + tokens_equal(primary, inventor_given, allow_initial=False) + for inventor_given in inventor.given_names + ): + return False + + for inventor_given in inventor.given_names: + if _initial_letter(inventor_given) and not any( + tokens_equal(author_given, inventor_given, allow_initial=False) + for author_given in author.given_names + ): + return False + + return True diff --git a/service/src/main/inse/patents/authors/name_variants.py b/service/src/main/inse/patents/authors/name_variants.py new file mode 100644 index 00000000..c1f7a5e0 --- /dev/null +++ b/service/src/main/inse/patents/authors/name_variants.py @@ -0,0 +1,111 @@ +"""Parse person names and build search/match variants for multi-part names.""" +from __future__ import annotations + +import re +from dataclasses import dataclass + +from inse.patents.common.text_normalization import normalize_name_part + +_NAME_SUFFIXES = frozenset({ + "dr", "prof", "mr", "mrs", "ms", "phd", "ph", "md", "jr", "sr", +}) + + +@dataclass(frozen=True) +class ParsedPersonName: + raw: str + tokens: tuple[str, ...] + given_names: tuple[str, ...] + last_name: str + compound_last_name: str | None + + @property + def is_single_token(self) -> bool: + return len(self.tokens) == 1 + + @property + def primary_given_name(self) -> str | None: + return self.given_names[0] if self.given_names else None + + +def parse_person_name(display_name: str | None) -> ParsedPersonName | None: + if not display_name or not display_name.strip(): + return None + + cleaned = _strip_name_suffixes(display_name.strip()) + tokens = tuple(part for part in cleaned.split() if part) + if not tokens: + return None + + if len(tokens) == 1: + return ParsedPersonName( + raw=display_name.strip(), + tokens=tokens, + given_names=(), + last_name=tokens[0], + compound_last_name=None, + ) + + given_names = tokens[:-1] + last_name = tokens[-1] + compound_last_name = " ".join(tokens[-2:]) if len(tokens) >= 3 else None + + return ParsedPersonName( + raw=display_name.strip(), + tokens=tokens, + given_names=given_names, + last_name=last_name, + compound_last_name=compound_last_name, + ) + + +def parse_inventor_name(inventor_name: str | None) -> ParsedPersonName | None: + if not inventor_name or not inventor_name.strip(): + return None + + cleaned = _strip_name_suffixes(inventor_name.strip()) + if "," in cleaned: + last_part, first_part = [part.strip() for part in cleaned.split(",", 1)] + family_tokens = tuple(token for token in last_part.split() if token) + given_tokens = tuple(token for token in first_part.split() if token) + if not family_tokens: + return None + tokens = given_tokens + family_tokens + return ParsedPersonName( + raw=inventor_name.strip(), + tokens=tokens, + given_names=given_tokens, + last_name=family_tokens[-1], + compound_last_name=( + " ".join(family_tokens) + if len(family_tokens) > 1 + else None + ), + ) + + return parse_person_name(cleaned) + + +def _strip_name_suffixes(name: str) -> str: + parts = [part.strip() for part in name.split(",")] + while len(parts) > 1 and _is_name_suffix(parts[-1]): + parts = parts[:-1] + return ", ".join(parts).strip() + + +def _is_name_suffix(value: str) -> bool: + normalized = normalize_name_part(value).rstrip(".") + return normalized in _NAME_SUFFIXES + + +def _initials_from_tokens(tokens: list[str]) -> str: + initials = "" + for token in tokens: + normalized = normalize_name_part(token) + if not normalized: + continue + if len(normalized) == 1: + initials += normalized.upper() + else: + initials += normalized[0].upper() + return initials diff --git a/service/src/main/inse/patents/authors/profile.py b/service/src/main/inse/patents/authors/profile.py new file mode 100644 index 00000000..7c4ca646 --- /dev/null +++ b/service/src/main/inse/patents/authors/profile.py @@ -0,0 +1,194 @@ +"""Build a structured author profile for patent disambiguation.""" +from __future__ import annotations + +import logging +from dataclasses import dataclass, field + +from inse import config +from inse.integrations import elasticsearch +from inse.models.openalex.author import Author +from inse.patents.authors.name_frequency import is_common_name, is_single_token_name +from inse.patents.authors.name_matching import ( + name_matches_person, +) +from inse.patents.authors.name_variants import parse_inventor_name, parse_person_name + +logger = logging.getLogger(__name__) + +CO_AUTHOR_WORK_LIMIT = 25 + + +@dataclass(frozen=True) +class AuthorTopic: + display_name: str + score: float = 0.0 + + +@dataclass +class AuthorProfile: + author_id: str + display_name: str + first_name: str | None + last_name: str | None + is_single_token: bool + is_common_name: bool + institutions: list[str] = field(default_factory=list) + topics: list[AuthorTopic] = field(default_factory=list) + co_author_names: list[str] = field(default_factory=list) + + @property + def topic_display_names(self) -> list[str]: + return [topic.display_name for topic in self.topics if topic.display_name] + + +def extract_last_name(name: str | None) -> str | None: + parsed = parse_person_name(name) + return parsed.last_name if parsed else None + + +def extract_first_name(name: str | None) -> str | None: + parsed = parse_person_name(name) + return parsed.primary_given_name if parsed else None + + +def _normalize_author_id(author_id: str) -> str: + return author_id.replace("https://openalex.org/", "").strip() + + +def _institution_names(author: Author) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + + for institution in author.last_known_institutions or []: + display_name = institution.display_name + if not display_name: + continue + key = display_name.casefold() + if key in seen: + continue + seen.add(key) + names.append(display_name) + + for affiliation in author.affiliations or []: + institution = affiliation.institution + if not institution or not institution.display_name: + continue + key = institution.display_name.casefold() + if key in seen: + continue + seen.add(key) + names.append(institution.display_name) + + return names + + +def _author_topics(author: Author) -> list[AuthorTopic]: + topics: list[AuthorTopic] = [] + for topic in author.topics or []: + if not topic.display_name: + continue + score = float(topic.score or 0.0) + topics.append(AuthorTopic(display_name=topic.display_name, score=score)) + topics.sort(key=lambda item: item.score, reverse=True) + return topics[:15] + + +def _fetch_co_author_names(author_id: str, display_name: str) -> list[str]: + short_id = _normalize_author_id(author_id) + author_url = f"https://openalex.org/{short_id}" + normalized_self = display_name.casefold().strip() + + body = { + "size": CO_AUTHOR_WORK_LIMIT, + "sort": [{"cited_by_count": {"order": "desc"}}], + "_source": ["authorships"], + "query": { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [{"term": {"authorships.author.id": author_url}}], + } + }, + } + }, + } + + try: + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + except Exception: + logger.warning("Co-author lookup failed for author %s", short_id, exc_info=True) + return [] + + co_authors: list[str] = [] + seen: set[str] = set() + + for hit in response.get("hits", {}).get("hits", []): + for authorship in hit.get("_source", {}).get("authorships", []): + author = authorship.get("author") or {} + co_author_name = (author.get("display_name") or "").strip() + if not co_author_name: + continue + key = co_author_name.casefold() + if key == normalized_self or key in seen: + continue + seen.add(key) + co_authors.append(co_author_name) + + return co_authors[:40] + + +def build_author_profile( + author: Author, + *, + patent_hit_count: int | None = None, + fetch_co_authors: bool = True, +) -> AuthorProfile: + author_id = _normalize_author_id(author.id or "") + display_name = (author.display_name or "").strip() + first_name = extract_first_name(display_name) + last_name = extract_last_name(display_name) + + co_author_names: list[str] = [] + if fetch_co_authors and author_id: + co_author_names = _fetch_co_author_names(author_id, display_name) + + return AuthorProfile( + author_id=author_id, + display_name=display_name, + first_name=first_name, + last_name=last_name, + is_single_token=is_single_token_name(display_name), + is_common_name=is_common_name( + display_name, + last_name, + first_name=first_name, + patent_hit_count=patent_hit_count, + ), + institutions=_institution_names(author), + topics=_author_topics(author), + co_author_names=co_author_names, + ) + + +def inventor_last_name(inventor_name: str) -> str: + name = inventor_name.strip() + if "," in name: + last_part, _ = [part.strip() for part in name.split(",", 1)] + return last_part.split()[0] if last_part else "" + parts = name.split() + return parts[-1] if parts else "" + + +def inventor_first_name(inventor_name: str) -> str: + parsed = parse_inventor_name(inventor_name) + return parsed.primary_given_name or "" + + +def inventor_matches_co_author(inventor_name: str, co_author_name: str) -> bool: + if not inventor_name or not co_author_name: + return False + return name_matches_person(inventor_name, co_author_name) diff --git a/service/src/main/inse/patents/authors/scoring.py b/service/src/main/inse/patents/authors/scoring.py new file mode 100644 index 00000000..36b58186 --- /dev/null +++ b/service/src/main/inse/patents/authors/scoring.py @@ -0,0 +1,201 @@ +"""Score patent matches against an author profile.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from inse.patents.authors.name_matching import ( + first_name_match_kind_for_person, + name_matches_person, + tokens_equal, +) +from inse.patents.authors.profile import ( + AuthorProfile, + inventor_last_name, + inventor_matches_co_author, +) +from inse.patents.authors.topic_matching import ( + TopicMatchResult, + has_topic_conflict, + match_patent_topics, +) +from inse.patents.common import model +from inse.patents.institutions.name_matching import assignee_matches_institution_name + +NameMatchKind = Literal["full", "initial", "none"] +MatchConfidence = Literal["high", "medium", "uncertain"] + +SCORE_NAME_FULL = 0.40 +SCORE_NAME_INITIAL = 0.25 +SCORE_INSTITUTION = 0.35 +SCORE_CO_AUTHOR = 0.30 +SCORE_TOPIC_STRONG = 0.25 +SCORE_TOPIC_WEAK = 0.10 +SCORE_PERSONAL_ASSIGNEE = 0.25 + + +@dataclass(frozen=True) +class PatentMatchScore: + patent: model.PatentEntry + score: float + confidence: MatchConfidence + name_match: NameMatchKind + institution_match: bool + co_author_match: bool + personal_assignee_match: bool + topic_match: TopicMatchResult + topic_conflict: bool + badges: tuple[str, ...] + reasons: tuple[str, ...] + + @property + def has_strong_context(self) -> bool: + return ( + self.institution_match + or self.co_author_match + or self.personal_assignee_match + or self.topic_match.level == "strong" + ) + + +def _best_name_match(patent: model.PatentEntry, profile: AuthorProfile) -> NameMatchKind: + if profile.is_single_token and profile.last_name: + for inventor in patent.inventors: + if tokens_equal( + inventor_last_name(inventor), + profile.last_name, + allow_initial=False, + ): + return "full" + return "none" + + if not profile.first_name or not profile.last_name: + return "none" + + best: NameMatchKind = "none" + for inventor in patent.inventors: + if not name_matches_person(inventor, profile.display_name): + continue + kind = first_name_match_kind_for_person(inventor, profile.display_name) + if kind == "full": + return "full" + if kind == "initial": + best = "initial" + return best + + +def _personal_assignee_match(patent: model.PatentEntry, profile: AuthorProfile) -> bool: + if profile.is_single_token and profile.last_name: + for assignee in patent.assignees: + if tokens_equal( + inventor_last_name(assignee), + profile.last_name, + allow_initial=False, + ): + return True + return False + + if not profile.first_name or not profile.last_name: + return False + + for assignee in patent.assignees: + if name_matches_person(assignee, profile.display_name): + return True + return False + + +def _institution_match(patent: model.PatentEntry, profile: AuthorProfile) -> bool: + if not profile.institutions: + return False + for assignee in patent.assignees: + for institution_name in profile.institutions: + if assignee_matches_institution_name(assignee, institution_name): + return True + return False + + +def _co_author_match(patent: model.PatentEntry, profile: AuthorProfile) -> bool: + if not profile.co_author_names: + return False + for inventor in patent.inventors: + for co_author_name in profile.co_author_names: + if inventor_matches_co_author(inventor, co_author_name): + return True + return False + + +def _confidence(score: float) -> MatchConfidence: + if score >= 0.75: + return "high" + if score >= 0.6: + return "medium" + return "uncertain" + + +def score_patent(patent: model.PatentEntry, profile: AuthorProfile) -> PatentMatchScore: + name_match = _best_name_match(patent, profile) + institution_match = _institution_match(patent, profile) + co_author_match = _co_author_match(patent, profile) + personal_assignee_match = _personal_assignee_match(patent, profile) + topic_match = match_patent_topics(patent, profile.topic_display_names) + topic_conflict = has_topic_conflict(patent, profile.topic_display_names) + + score = 0.0 + badges: list[str] = [] + reasons: list[str] = [] + + if name_match == "full": + score += SCORE_NAME_FULL + badges.append("Name") + reasons.append("Vollständiger Namensabgleich") + elif name_match == "initial": + score += SCORE_NAME_INITIAL + badges.append("Name") + reasons.append("Namensabgleich per Initial") + + if institution_match: + score += SCORE_INSTITUTION + badges.append("Institution") + reasons.append("Institution passt zum Patent-Anmelder") + + if co_author_match: + score += SCORE_CO_AUTHOR + badges.append("Co-Autor") + reasons.append("Bekannter Co-Autor als Mit-Erfinder") + + if personal_assignee_match: + score += SCORE_PERSONAL_ASSIGNEE + badges.append("Anmelder") + reasons.append("Persönliche Patentanmeldung des Autors") + + if topic_match.level == "strong": + score += SCORE_TOPIC_STRONG + badges.append("Thema") + reasons.append("Fachgebiet stimmt mit Publikationsthemen überein") + elif topic_match.level == "weak": + score += SCORE_TOPIC_WEAK + badges.append("Thema") + reasons.append("Schwaches Themensignal im Patenttext") + + score = min(score, 1.0) + + return PatentMatchScore( + patent=patent, + score=round(score, 3), + confidence=_confidence(score), + name_match=name_match, + institution_match=institution_match, + co_author_match=co_author_match, + personal_assignee_match=personal_assignee_match, + topic_match=topic_match, + topic_conflict=topic_conflict, + badges=tuple(badges), + reasons=tuple(reasons), + ) + + +def score_patents( + patents: list[model.PatentEntry], + profile: AuthorProfile, +) -> list[PatentMatchScore]: + return [score_patent(patent, profile) for patent in patents] diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py index 2149fa98..5d6a14c4 100644 --- a/service/src/main/inse/patents/authors/search_queries.py +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -1,7 +1,8 @@ """Elasticsearch query builders for inventor-based patent search.""" from typing import Any -from inse.patents.authors.name_matching import search_name_variants +from inse.patents.authors.name_matching import inventor_search_phrases, search_name_variants +from inse.patents.authors.name_variants import parse_person_name from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE @@ -17,32 +18,51 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]: } +def _match_any_phrase_field(field: str, phrases: list[str]) -> dict[str, Any]: + if not phrases: + return {"match_none": {}} + if len(phrases) == 1: + return {"match": {field: phrases[0]}} + return { + "bool": { + "should": [{"match": {field: phrase}} for phrase in phrases], + "minimum_should_match": 1, + } + } + + class InventorSearchQueries: def epo_query_by_inventor( self, - last_name: str, + display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - if first_name: + if first_name and display_name and " " not in display_name.strip(): + display_name = f"{first_name} {display_name}".strip() + + parsed = parse_person_name(display_name) + if parsed is None: + query = {"match_none": {}} + elif parsed.is_single_token: query = { "nested": { "path": "inventors_name_nested", - "query": { - "bool": { - "must": [ - _match_name_field("inventors_name_nested.inventor", last_name), - _match_name_field("inventors_name_nested.inventor", first_name), - ] - } - }, + "query": _match_name_field( + "inventors_name_nested.inventor", + parsed.last_name, + ), } } else: + phrases = inventor_search_phrases(display_name) query = { "nested": { "path": "inventors_name_nested", - "query": _match_name_field("inventors_name_nested.inventor", last_name), + "query": _match_any_phrase_field( + "inventors_name_nested.inventor", + phrases, + ), } } @@ -75,29 +95,29 @@ class InventorSearchQueries: def uspto_query_by_inventor( self, - last_name: str, + display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - if first_name: + if first_name and display_name and " " not in display_name.strip(): + display_name = f"{first_name} {display_name}".strip() + + parsed = parse_person_name(display_name) + if parsed is None: + query = {"match_none": {}} + elif parsed.is_single_token: query = { "nested": { "path": "inventors", - "query": { - "bool": { - "must": [ - _match_name_field("inventors.name", last_name), - _match_name_field("inventors.name", first_name), - ] - } - }, + "query": _match_name_field("inventors.name", parsed.last_name), } } else: + phrases = inventor_search_phrases(display_name) query = { "nested": { "path": "inventors", - "query": _match_name_field("inventors.name", last_name), + "query": _match_any_phrase_field("inventors.name", phrases), } } diff --git a/service/src/main/inse/patents/authors/test_disambiguation.py b/service/src/main/inse/patents/authors/test_disambiguation.py new file mode 100644 index 00000000..aa908728 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_disambiguation.py @@ -0,0 +1,308 @@ +import pytest + +from inse.patents.authors.filtering import filter_scored_patents, to_matched_patent_entry +from inse.patents.authors.name_frequency import ( + is_common_name, + is_single_token_name, + score_threshold, +) +from inse.patents.authors.profile import AuthorProfile, AuthorTopic +from inse.patents.authors.scoring import score_patent +from inse.patents.authors.topic_matching import ( + extract_specific_topic_tokens, + has_topic_conflict, + match_patent_topics, +) +from inse.patents.common import model + + +def _profile( + *, + display_name: str = "Anna Becker", + first_name: str = "Anna", + last_name: str = "Becker", + is_common: bool = False, + is_single_token: bool = False, + institutions: list[str] | None = None, + topics: list[str] | None = None, + co_authors: list[str] | None = None, +) -> AuthorProfile: + return AuthorProfile( + author_id="A123", + display_name=display_name, + first_name=first_name, + last_name=last_name, + is_single_token=is_single_token, + is_common_name=is_common, + institutions=institutions or [], + topics=[ + AuthorTopic(display_name=name, score=1.0) + for name in (topics or []) + ], + co_author_names=co_authors or [], + ) + + +def _patent( + *, + title: str, + abstract: str | None = None, + inventors: list[str] | None = None, + assignees: list[str] | None = None, +) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP123", + source="EPO", + title=title, + abstract=abstract, + inventors=inventors or ["Becker, Anna"], + assignees=assignees or [], + ) + + +def test_is_single_token_name_detects_einnamen() -> None: + assert is_single_token_name("Priti") + assert not is_single_token_name("Anna Becker") + + +def test_is_common_name_for_single_token_and_frequent_last_name() -> None: + assert is_common_name("Priti", "Priti") + assert is_common_name("John Smith", "Smith", first_name="John") + assert not is_common_name("Xaver Uncommon", "Uncommon", first_name="Xaver") + assert is_common_name("John Smith", "Smith", first_name="John", patent_hit_count=500) + assert not is_common_name( + "Pedro José Marrón", + "Marrón", + first_name="Pedro", + patent_hit_count=500, + ) + + +def test_score_threshold_depends_on_name_shape() -> None: + assert score_threshold(True) == 0.8 + assert score_threshold(False) == 0.6 + + +def test_extract_specific_topic_tokens_ignores_generic_terms() -> None: + tokens = extract_specific_topic_tokens("Cell biology and molecular methods") + assert "cell" not in tokens + assert "molecular" not in tokens + assert "biology" not in tokens + assert "methods" not in tokens + + +def test_topic_match_requires_two_specific_terms() -> None: + patent = _patent( + title="Cardiac arrhythmia monitoring device", + abstract="Methods for heart rhythm analysis", + ) + result = match_patent_topics( + patent, + ["Cardiac arrhythmia and heart rhythm disorders"], + ) + assert result.level == "strong" + assert len(result.matched_terms) >= 2 + + +def test_topic_match_weak_with_single_specific_term() -> None: + patent = _patent(title="Arrhythmia overview") + result = match_patent_topics(patent, ["Cardiac arrhythmia disorders"]) + assert result.level == "weak" + + +def test_topic_conflict_between_cardiology_and_tires() -> None: + patent = _patent( + title="Vehicle pneumatic tyre and rubber tread", + abstract="Automotive tire manufacturing process", + ) + assert has_topic_conflict( + patent, + ["Cardiac arrhythmia and coronary artery disease"], + ) + + +def test_name_only_match_rejected_for_uncommon_name_below_threshold() -> None: + profile = _profile(topics=["Cardiac arrhythmia disorders"]) + scored = score_patent( + _patent(title="Unrelated mechanical widget"), + profile, + ) + filtered = filter_scored_patents([scored], profile) + assert filtered == [] + + +def test_institution_match_allows_non_conflicting_patent() -> None: + profile = _profile( + institutions=["University of Duisburg-Essen"], + topics=["Wireless sensor networks"], + ) + patent = _patent( + title="Energy efficient wireless sensor routing", + abstract="Routing protocols for sensor networks", + assignees=["University of Duisburg-Essen"], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert len(filtered) == 1 + assert filtered[0].institution_match + + +def test_common_name_rejected_without_strong_context() -> None: + profile = _profile( + display_name="John Smith", + first_name="John", + last_name="Smith", + is_common=True, + topics=["Cardiac arrhythmia disorders"], + ) + patent = _patent( + title="Cardiac arrhythmia monitoring", + abstract="Heart rhythm monitoring system", + inventors=["Smith, John"], + ) + scored = score_patent(patent, profile) + assert scored.topic_match.level in {"strong", "weak"} + filtered = filter_scored_patents([scored], profile) + assert filtered == [] + + +def test_common_name_accepted_with_institution_match() -> None: + profile = _profile( + display_name="John Smith", + first_name="John", + last_name="Smith", + is_common=True, + institutions=["University of Duisburg-Essen"], + ) + patent = _patent( + title="Generic engineering method", + assignees=["University of Duisburg-Essen"], + inventors=["Smith, John"], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert len(filtered) == 1 + + +def test_topic_conflict_rejected_without_rescue_signal() -> None: + profile = _profile(topics=["Cardiac arrhythmia and coronary artery disease"]) + patent = _patent( + title="Vehicle pneumatic tyre and rubber tread", + abstract="Automotive tire tread composition", + inventors=["Becker, Anna"], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert filtered == [] + + +def test_topic_conflict_allowed_with_co_author_match() -> None: + profile = _profile( + topics=["Cardiac arrhythmia and coronary artery disease"], + co_authors=["Maria Wagner"], + ) + patent = _patent( + title="Vehicle pneumatic tyre and rubber tread", + abstract="Automotive tire tread composition", + inventors=["Becker, Anna", "Wagner, Maria"], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert len(filtered) == 1 + assert filtered[0].co_author_match + + +def test_single_token_name_requires_higher_score() -> None: + profile = _profile( + display_name="Priti", + first_name=None, + last_name="Priti", + is_single_token=True, + is_common=True, + institutions=["University of Duisburg-Essen"], + ) + weak_patent = _patent( + title="Generic method", + assignees=["University of Duisburg-Essen"], + inventors=["Priti"], + ) + weak_scored = score_patent(weak_patent, profile) + assert filter_scored_patents([weak_scored], profile) == [] + + strong_patent = _patent( + title="Wireless sensor routing protocol", + abstract="Energy efficient sensor network routing", + assignees=["University of Duisburg-Essen"], + inventors=["Priti"], + ) + profile_with_topics = _profile( + display_name="Priti", + first_name=None, + last_name="Priti", + is_single_token=True, + is_common=True, + institutions=["University of Duisburg-Essen"], + topics=["Energy efficient wireless sensor networks"], + ) + strong_scored = score_patent(strong_patent, profile_with_topics) + assert len(filter_scored_patents([strong_scored], profile_with_topics)) == 1 + + +def test_to_matched_patent_entry_exposes_score_and_reasons() -> None: + profile = _profile( + institutions=["University of Duisburg-Essen"], + topics=["Wireless sensor networks"], + ) + patent = _patent( + title="Energy efficient wireless sensor routing", + abstract="Routing protocols for sensor networks", + assignees=["University of Duisburg-Essen"], + ) + scored = score_patent(patent, profile) + matched = to_matched_patent_entry(scored, profile) + assert matched.match_score >= 0.6 + assert matched.match_confidence in {"high", "medium"} + assert matched.match_badges + assert matched.match_reasons + + +def test_common_name_with_personal_assignee_is_kept() -> None: + profile = _profile( + display_name="John Smith", + first_name="John", + last_name="Smith", + is_common=True, + ) + patent = _patent( + title="Card reader apparatus", + inventors=["Smith, John"], + assignees=["Smith, John"], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert len(filtered) == 1 + + +def test_uncommon_full_name_without_context_is_kept_when_no_topic_conflict() -> None: + profile = _profile( + display_name="Pedro José Marrón", + first_name="Pedro", + last_name="Marrón", + topics=[ + "Energy Efficient Wireless Sensor Networks", + "Indoor and Outdoor Localization Technologies", + ], + ) + patent = _patent( + title="Card and reader/writer apparatus for cards", + abstract="A card and a read-write device for cards", + inventors=["Marron, Pedro José, Dr."], + assignees=["Marron, Pedro José, Dr."], + ) + scored = score_patent(patent, profile) + filtered = filter_scored_patents([scored], profile) + assert len(filtered) == 1 + matched = to_matched_patent_entry(filtered[0], profile) + assert matched.patent_id == "EP123" + assert matched.match_score >= 0.6 + assert matched.match_confidence == "medium" diff --git a/service/src/main/inse/patents/authors/topic_matching.py b/service/src/main/inse/patents/authors/topic_matching.py new file mode 100644 index 00000000..707c516c --- /dev/null +++ b/service/src/main/inse/patents/authors/topic_matching.py @@ -0,0 +1,176 @@ +"""Stricter topic matching between OpenAlex author topics and patent text.""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Literal + +from inse.patents.common.text_normalization import normalize_name_part +from inse.patents.common import model + +GENERIC_TOPIC_TERMS: frozenset[str] = frozenset({ + "cell", "cells", "molecular", "biology", "method", "methods", "system", "systems", + "process", "processes", "device", "devices", "apparatus", "composition", "use", + "using", "based", "related", "novel", "improved", "improvement", "treatment", + "analysis", "study", "studies", "research", "data", "model", "models", "control", + "structure", "material", "materials", "production", "application", "applications", + "field", "type", "types", "new", "high", "low", "general", "specific", "various", + "different", "multiple", "single", "first", "second", "third", "one", "two", + "three", "human", "humans", "animal", "animals", "plant", "plants", "water", + "energy", "power", "electronic", "electrical", "mechanical", "chemical", + "physical", "digital", "computer", "computing", "network", "networks", "wireless", + "optical", "medical", "clinical", "health", "disease", "diseases", "therapy", + "therapeutic", "pharmaceutical", "drug", "drugs", "agent", "agents", "compound", + "compounds", "protein", "proteins", "gene", "genes", "genetic", "genomic", + "expression", "function", "functional", "activity", "active", "inhibition", + "inhibitor", "inhibitors", "receptor", "receptors", "signaling", "pathway", + "pathways", "immune", "immunity", "inflammatory", "inflammation", "cancer", + "tumor", "tumour", "cardiac", "cardiovascular", "neural", "brain", "neuronal", +}) + +DOMAIN_KEYWORDS: dict[str, frozenset[str]] = { + "medical": frozenset({ + "cardiac", "cardiology", "heart", "arrhythmia", "myocardial", "coronary", + "surgical", "surgery", "hospital", "patient", "clinical", "diagnostic", + "therapeutic", "pharmaceutical", "oncology", "tumor", "cancer", "neurology", + "stroke", "dialysis", "prosthesis", "implant", "stent", "catheter", + }), + "automotive": frozenset({ + "tyre", "tire", "tires", "tyres", "pneumatic", "vehicle", "vehicles", + "automotive", "automobile", "brake", "braking", "chassis", "engine", + "powertrain", "transmission", "suspension", "exhaust", "windshield", + "rubber", "tread", "wheel", "wheels", "axle", "steering", + }), + "software": frozenset({ + "software", "algorithm", "algorithms", "database", "server", "cloud", + "blockchain", "cryptography", "encryption", "compiler", "api", "middleware", + "virtualization", "container", "kubernetes", "microservice", + }), + "chemistry": frozenset({ + "catalyst", "catalytic", "polymer", "polymeric", "synthesis", "solvent", + "electrolyte", "nanoparticle", "nanocomposite", "adsorbent", "chromatography", + }), + "agriculture": frozenset({ + "crop", "crops", "fertilizer", "pesticide", "herbicide", "livestock", + "irrigation", "harvest", "seed", "seeds", "agronomic", "soil", + }), +} + +TopicMatchLevel = Literal["strong", "weak", "none"] + + +@dataclass(frozen=True) +class TopicMatchResult: + level: TopicMatchLevel + matched_terms: tuple[str, ...] + matched_topic: str | None + + +def _tokenize_text(text: str) -> set[str]: + normalized = normalize_name_part(text) + if not normalized: + return set() + return {token for token in normalized.split() if len(token) >= 3} + + +def extract_specific_topic_tokens(topic_display_name: str) -> set[str]: + normalized = normalize_name_part(topic_display_name) + if not normalized: + return set() + + tokens: set[str] = set() + for token in re.split(r"[\s/\-]+", normalized): + if len(token) < 4: + continue + if token in GENERIC_TOPIC_TERMS: + continue + tokens.add(token) + return tokens + + +def patent_search_text(patent: model.PatentEntry) -> str: + parts = [patent.title or "", patent.abstract or ""] + for classification in patent.ipc_descriptions: + for value in ( + classification.section, + classification.ipc_class, + classification.subclass, + ): + if value: + parts.append(value) + return " ".join(parts) + + +def match_patent_topics( + patent: model.PatentEntry, + topic_display_names: list[str], +) -> TopicMatchResult: + if not topic_display_names: + return TopicMatchResult(level="none", matched_terms=(), matched_topic=None) + + patent_tokens = _tokenize_text(patent_search_text(patent)) + if not patent_tokens: + return TopicMatchResult(level="none", matched_terms=(), matched_topic=None) + + best_topic: str | None = None + best_matches: set[str] = set() + + for topic_name in topic_display_names: + specific_tokens = extract_specific_topic_tokens(topic_name) + if not specific_tokens: + continue + matched = specific_tokens & patent_tokens + if len(matched) > len(best_matches): + best_matches = matched + best_topic = topic_name + + if len(best_matches) >= 2: + return TopicMatchResult( + level="strong", + matched_terms=tuple(sorted(best_matches)), + matched_topic=best_topic, + ) + if len(best_matches) == 1: + return TopicMatchResult( + level="weak", + matched_terms=tuple(sorted(best_matches)), + matched_topic=best_topic, + ) + return TopicMatchResult(level="none", matched_terms=(), matched_topic=None) + + +def _domains_for_text(text: str) -> set[str]: + tokens = _tokenize_text(text) + matched_domains: set[str] = set() + for domain, keywords in DOMAIN_KEYWORDS.items(): + if len(keywords & tokens) >= 2: + matched_domains.add(domain) + return matched_domains + + +def _author_domains(topic_display_names: list[str]) -> set[str]: + domains: set[str] = set() + combined = " ".join(topic_display_names) + domains |= _domains_for_text(combined) + for topic_name in topic_display_names: + domains |= _domains_for_text(topic_name) + return domains + + +def has_topic_conflict( + patent: model.PatentEntry, + topic_display_names: list[str], +) -> bool: + if not topic_display_names: + return False + + author_domains = _author_domains(topic_display_names) + if not author_domains: + return False + + patent_domains = _domains_for_text(patent_search_text(patent)) + if not patent_domains: + return False + + conflicting = patent_domains - author_domains + return bool(conflicting) diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index b3cc97a4..38351b50 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -1,3 +1,5 @@ +from typing import Literal + from pydantic import BaseModel, ConfigDict, Field @@ -34,11 +36,22 @@ class PatentEntry(BaseModel): country: str | None = None +MatchConfidence = Literal["high", "medium"] + + +class MatchedPatentEntry(PatentEntry): + match_score: float + match_confidence: MatchConfidence + match_badges: list[str] = Field(default_factory=list) + match_reasons: list[str] = Field(default_factory=list) + + class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[PatentEntry] + is_common_name: bool = False + patents: list[MatchedPatentEntry] class PatentsByInstitutionResponse(BaseModel): diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py index 0b3cdf3b..ce4fea7e 100644 --- a/service/src/main/inse/patents/common/parsing.py +++ b/service/src/main/inse/patents/common/parsing.py @@ -11,6 +11,13 @@ from inse.patents.ipc_search_client import IpcSearchClient logger = logging.getLogger(__name__) +def parse_search_total(data: dict) -> int: + total = data.get("hits", {}).get("total") + if isinstance(total, dict): + return int(total.get("value", 0)) + return int(total or 0) + + def parse_epo_hits(data: dict) -> list[model.PatentEntry]: patents = [] for hit in data.get("hits", {}).get("hits", []): diff --git a/service/src/main/inse/patents/name_matching.py b/service/src/main/inse/patents/name_matching.py index a1e45065..c40ce50c 100644 --- a/service/src/main/inse/patents/name_matching.py +++ b/service/src/main/inse/patents/name_matching.py @@ -1,7 +1,10 @@ """Backward-compatible re-exports.""" from inse.patents.authors.name_matching import ( # noqa: F401 first_name_match_kind, + first_name_match_kind_for_person, + inventor_search_phrases, name_matches, + name_matches_person, search_name_variants, tokens_equal, ) diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index 4e8f8308..44e8e2f0 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -12,13 +12,17 @@ from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.integrations import elasticsearch from inse.models.openalex.author import Author -from inse.patents.authors.name_matching import name_matches +from inse.patents.authors.filtering import disambiguate_patents, patent_from_matched +from inse.patents.authors.name_matching import name_matches_person, tokens_equal +from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.profile import build_author_profile, inventor_last_name from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.model import PatentEntry from inse.patents.common.parsing import ( deduplicate_patents, enrich_patents_classifications, parse_epo_hits, + parse_search_total, parse_uspto_hits, patent_dedup_key, ) @@ -55,21 +59,45 @@ def _extract_first_name(name: str | None) -> str | None: return parts[0] if len(parts) > 1 else None -def _filter_patents_by_name( +def _filter_patents_by_last_name( patents: list[PatentEntry], - first_name: str, last_name: str, ) -> list[PatentEntry]: return [ patent for patent in patents if any( - name_matches(inventor, first_name, last_name) + tokens_equal(inventor_last_name(inventor), last_name, allow_initial=False) for inventor in patent.inventors ) ] +def _filter_patents_by_display_name( + patents: list[PatentEntry], + display_name: str, +) -> list[PatentEntry]: + return [ + patent + for patent in patents + if any( + name_matches_person(inventor, display_name) + for inventor in patent.inventors + ) + ] + + +def _filter_patents_by_name( + patents: list[PatentEntry], + first_name: str, + last_name: str, +) -> list[PatentEntry]: + return _filter_patents_by_display_name( + patents, + f"{first_name} {last_name}".strip(), + ) + + @dataclass class _AccumulatedPatent: patent: PatentEntry @@ -256,8 +284,8 @@ async def _search_patents_by_author( search_client: PatentSearchClient, ) -> list[PatentEntry]: author_name = author.display_name + parsed_name = parse_person_name(author_name) last_name = _extract_last_name(author_name) - first_name = _extract_first_name(author_name) if not last_name: return [] @@ -265,12 +293,14 @@ async def _search_patents_by_author( epo_data, uspto_data = await asyncio.gather( search_client.search_epo( search_client.epo_query_by_inventor( - last_name, first_name, size=ORG_PATENT_SEARCH_SIZE + author_name, + size=ORG_PATENT_SEARCH_SIZE, ) ), search_client.search_uspto( search_client.uspto_query_by_inventor( - last_name, first_name, size=ORG_PATENT_SEARCH_SIZE + author_name, + size=ORG_PATENT_SEARCH_SIZE, ) ), ) @@ -278,9 +308,16 @@ async def _search_patents_by_author( raise patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - if first_name and last_name: - patents = _filter_patents_by_name(patents, first_name, last_name) - return deduplicate_patents(patents) + if parsed_name and parsed_name.is_single_token: + patents = _filter_patents_by_last_name(patents, last_name) + elif author_name: + patents = _filter_patents_by_display_name(patents, author_name) + patents = deduplicate_patents(patents) + + patent_hit_count = parse_search_total(epo_data) + parse_search_total(uspto_data) + profile = build_author_profile(author, patent_hit_count=patent_hit_count) + matched_patents = disambiguate_patents(patents, profile) + return [patent_from_matched(entry) for entry in matched_patents] async def build_org_patents_for_institution( 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 9e12f5dd..613e2706 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -16,15 +16,14 @@ def anyio_backend(): def test_epo_query_uses_nested_search_and_name_variants(): client = PatentSearchClient(api_key="test-key") - payload = client.epo_query_by_inventor("Müller", "Christian") + payload = client.epo_query_by_inventor("Pedro José Marrón") assert payload["size"] == DEFAULT_SEARCH_SIZE assert payload["sort"][0] == {"_score": {"order": "desc"}} nested = payload["query"]["nested"] assert nested["path"] == "inventors_name_nested" - must = nested["query"]["bool"]["must"] - assert len(must) == 2 - assert "should" in must[0]["bool"] + inventor_query = nested["query"] + assert "should" in inventor_query["bool"] def test_uspto_index_is_3_0(): @@ -68,7 +67,7 @@ async def test_search_epo_posts_to_correct_index(): api_key="test-key", transport=httpx.MockTransport(handler), ) - await client.search_epo(client.epo_query_by_inventor("Weber", "Christian")) + 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 diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index cc93465d..1c086842 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -2,7 +2,10 @@ import pytest from inse.patents.name_matching import ( first_name_match_kind, + first_name_match_kind_for_person, + inventor_search_phrases, name_matches, + name_matches_person, name_token_variants, normalize_name_part, search_name_variants, @@ -52,7 +55,7 @@ def test_hyphenated_first_name() -> None: [ ("Christian Weber", "Christian", "Weber", True), ("Weber, Christian", "Christian", "Weber", True), - ("Marc Christian Weber", "Christian", "Weber", False), + ("Marc Christian Weber", "Christian", "Weber", True), ("Müller, Hans", "Hans", "Müller", True), ("Mueller, Hans", "Hans", "Müller", True), ("Hans Mueller", "Hans", "Müller", True), @@ -114,7 +117,47 @@ def test_name_matches_initials(inventor: str, first: str, last: str, expected: b def test_first_name_match_kind() -> None: assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full" assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial" - assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none" + assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "full" + + +@pytest.mark.parametrize( + ("inventor", "display_name", "expected"), + [ + ("Marrón, Pedro José", "Pedro José Marrón", True), + ("Marron, Pedro Jose, Dr.", "Pedro José Marrón", True), + ("P. J. Marrón", "Pedro José Marrón", True), + ("Schmidt, Anna Maria", "Anna Maria Schmidt", True), + ("Maria Schmidt", "Anna Maria Schmidt", True), + ("García López, Juan Carlos", "Juan Carlos García López", True), + ("López, Juan", "Juan Carlos García López", True), + ("Mohamed Ali Hassan", "Mohamed Ali Hassan", True), + ("Ali Hassan", "Mohamed Ali Hassan", True), + ], +) +def test_name_matches_person_multi_part( + inventor: str, + display_name: str, + expected: bool, +) -> None: + assert name_matches_person(inventor, display_name) is expected + + +def test_inventor_search_phrases_include_comma_and_initials() -> None: + phrases = inventor_search_phrases("Pedro José Marrón") + folded = {phrase.casefold() for phrase in phrases} + assert any("marron" in phrase and "pedro" in phrase for phrase in folded) + assert any("," in phrase for phrase in phrases) + + +def test_first_name_match_kind_multi_part() -> None: + assert ( + first_name_match_kind_for_person("Marrón, Pedro José", "Pedro José Marrón") + == "full" + ) + assert ( + first_name_match_kind_for_person("P. J. Marrón", "Pedro José Marrón") + == "initial" + ) def test_search_name_variants_includes_initial() -> None: diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 96c3842d..e9be4e50 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -29,3 +29,12 @@ export interface PatentEntry { country: string | null; } +export type MatchConfidence = 'high' | 'medium'; + +export interface MatchedPatentEntry extends PatentEntry { + match_score: number; + match_confidence: MatchConfidence; + match_badges: string[]; + match_reasons: string[]; +} + diff --git a/webapp/src/app/api/model/patentsByAuthorResponse.ts b/webapp/src/app/api/model/patentsByAuthorResponse.ts index ed970c7a..6576f9df 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -7,11 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { PatentEntry } from './patentEntry'; +import { MatchedPatentEntry } from './patentEntry'; export interface PatentsByAuthorResponse { author_id: string; author_name?: string | null; patent_count: number; - patents: Array; + is_common_name?: boolean; + patents: Array; } 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 085a9c9b..714044db 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -3,7 +3,7 @@ } @else if (error) {

Fehler beim Laden der Patente.

} @else if (patents.length === 0) { -

Keine Patente gefunden.

+

{{ getEmptyMessage() }}

} @else {
@@ -88,6 +88,14 @@ }
+ @if (selectedPatent.match_badges?.length) { +
+ @for (badge of selectedPatent.match_badges; track badge) { + {{ formatMatchBadgeLabel(badge) }} + } +
+ } + @if (getAbstractPreview(selectedPatent.abstract); as abstractPreview) {

{{ abstractPreview }}

} @@ -103,7 +111,7 @@ } @else {

Patentübersicht

-

Alle Patente dieser Person im Überblick.

+

Nur sicher zugeordnete Patente dieser Person.

{{ patents.length }} @@ -118,7 +126,7 @@ USPTO
-

Wähle links ein Patent aus, um Kurzinfos und Details zu sehen.

+

Wähle links ein Patent aus, um Details zu sehen.

}
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 37cac10f..68ec5480 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -97,6 +97,38 @@ } } +.match-badges { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 4px; +} + +.match-badge { + display: inline-flex; + align-items: center; + padding: 2px 8px; + border-radius: 999px; + background: #f3f4f6; + border: 1px solid #e5e7eb; + color: #374151; + font-size: 0.68rem; + font-weight: 600; + + &--signal { + padding: 4px 10px; + font-size: 0.75rem; + background: #ecfdf5; + border-color: #a7f3d0; + color: #047857; + } +} + +.match-badges--detail { + margin-top: 14px; + gap: 6px; +} + .source-badge { display: inline-flex; align-items: center; 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 b204fa09..340f71e5 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -2,7 +2,7 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; import { PatentsService } from '../../api/api/patents.service'; -import { PatentEntry } from '../../api/model/patentEntry'; +import { MatchedPatentEntry } from '../../api/model/patentEntry'; import { formatPatentDate, getPublicationStageLabel, @@ -22,10 +22,11 @@ export class PersonPatentsComponent implements OnInit { private router = inject(Router); private patentsApi = inject(PatentsService); - patents: PatentEntry[] = []; - filteredPatents: PatentEntry[] = []; + patents: MatchedPatentEntry[] = []; + filteredPatents: MatchedPatentEntry[] = []; authorName: string | null = null; - selectedPatent: PatentEntry | null = null; + isCommonName = false; + selectedPatent: MatchedPatentEntry | null = null; loading = true; error = false; @@ -55,6 +56,7 @@ export class PersonPatentsComponent implements OnInit { next: (result) => { this.patents = result.patents ?? []; this.authorName = result.author_name ?? null; + this.isCommonName = result.is_common_name ?? false; this.applyFilter(); this.loading = false; }, @@ -81,7 +83,7 @@ export class PersonPatentsComponent implements OnInit { this.updateQueryParams(); } - selectPatent(patent: PatentEntry): void { + selectPatent(patent: MatchedPatentEntry): void { this.selectedPatent = patent; this.updateQueryParams(); } @@ -101,7 +103,7 @@ export class PersonPatentsComponent implements OnInit { this.filteredPatents = this.sortPatents(patents); } - private sortPatents(patents: PatentEntry[]): PatentEntry[] { + private sortPatents(patents: MatchedPatentEntry[]): MatchedPatentEntry[] { return [...patents].sort((a, b) => { if (this.sortMode === 'date') { return (b.publication_date ?? '').localeCompare(a.publication_date ?? ''); @@ -130,7 +132,7 @@ export class PersonPatentsComponent implements OnInit { return value === 'date' || value === 'title'; } - getPagedPatents(): PatentEntry[] { + getPagedPatents(): MatchedPatentEntry[] { const start = (this.selectedPage - 1) * this.pageSize; return this.filteredPatents.slice(start, start + this.pageSize); } @@ -160,7 +162,7 @@ export class PersonPatentsComponent implements OnInit { return this.patents.filter((p) => p.source === 'USPTO').length; } - trackPatent(_index: number, patent: PatentEntry): string { + trackPatent(_index: number, patent: MatchedPatentEntry): string { return [ patent.source, patent.patent_id, @@ -180,7 +182,25 @@ export class PersonPatentsComponent implements OnInit { return `${text.slice(0, 160).trimEnd()}…`; } - getPublicationStageLabel(patent: PatentEntry): string | null { + getPublicationStageLabel(patent: MatchedPatentEntry): string | null { return getPublicationStageLabel(patent); } + + formatMatchBadgeLabel(badge: string): string { + const labels: Record = { + Name: 'Name passt', + Institution: 'Institution passt', + 'Co-Autor': 'Co-Autor passt', + Thema: 'Themenbereich passt', + Anmelder: 'Anmelder passt', + }; + return labels[badge] ?? badge; + } + + getEmptyMessage(): string { + if (this.isCommonName) { + return 'Keine sicheren Patentzuordnungen gefunden. Bei häufigen oder einteiligen Namen werden nur Patente mit starkem Kontext angezeigt.'; + } + return 'Keine sicheren Patentzuordnungen gefunden.'; + } }