From ca6c132bb9709efbca0dc8a4f84b6b50b19392d7 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 29 Jun 2026 19:27:26 +0200 Subject: [PATCH 01/60] feat(patents): score and filter patent-to-researcher matches --- .../main/inse/patents/authors/filtering.py | 127 ++++++++ .../src/main/inse/patents/authors/logic.py | 89 +++-- .../inse/patents/authors/name_frequency.py | 124 +++++++ .../inse/patents/authors/name_matching.py | 196 +++++++++-- .../inse/patents/authors/name_variants.py | 111 +++++++ .../src/main/inse/patents/authors/profile.py | 194 +++++++++++ .../src/main/inse/patents/authors/scoring.py | 201 ++++++++++++ .../inse/patents/authors/search_queries.py | 66 ++-- .../patents/authors/test_disambiguation.py | 308 ++++++++++++++++++ .../inse/patents/authors/topic_matching.py | 176 ++++++++++ service/src/main/inse/patents/common/model.py | 15 +- .../src/main/inse/patents/common/parsing.py | 7 + .../src/main/inse/patents/name_matching.py | 3 + service/src/main/inse/patents/org/logic.py | 57 +++- .../patents/test_elastic_search_client.py | 9 +- .../main/inse/patents/test_name_matching.py | 47 ++- webapp/src/app/api/model/patentEntry.ts | 9 + .../app/api/model/patentsByAuthorResponse.ts | 5 +- .../person-patents.component.html | 14 +- .../person-patents.component.scss | 32 ++ .../person-patents.component.ts | 38 ++- 21 files changed, 1718 insertions(+), 110 deletions(-) create mode 100644 service/src/main/inse/patents/authors/filtering.py create mode 100644 service/src/main/inse/patents/authors/name_frequency.py create mode 100644 service/src/main/inse/patents/authors/name_variants.py create mode 100644 service/src/main/inse/patents/authors/profile.py create mode 100644 service/src/main/inse/patents/authors/scoring.py create mode 100644 service/src/main/inse/patents/authors/test_disambiguation.py create mode 100644 service/src/main/inse/patents/authors/topic_matching.py 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.'; + } } From 513489e7907ab2e0f2672258c60be618eb678a05 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 29 Jun 2026 19:59:31 +0200 Subject: [PATCH 02/60] fix(patents): await async person and co-author lookups after dev merge --- service/src/main/inse/patents/authors/logic.py | 8 ++++---- service/src/main/inse/patents/authors/profile.py | 8 ++++---- service/src/main/inse/patents/org/logic.py | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 55b1c4b4..07086c23 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -41,7 +41,7 @@ async def get_patents_by_author_id( search_client = client or PatentSearchClient() ipc_search_client = ipc_client or IpcSearchClient() - author = _get_author(author_id) + author = await _get_author(author_id) if not author: return model.PatentsByAuthorResponse( author_id=author_id, @@ -86,7 +86,7 @@ async def get_patents_by_author_id( all_patents = deduplicate_patents(all_patents) - profile = build_author_profile( + profile = await build_author_profile( author, patent_hit_count=patent_hit_count, ) @@ -141,7 +141,7 @@ def _filter_patents_by_last_name( ] -def _get_author(author_id: str) -> Author | None: +async 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) + result = await person_logic.search_persons(author_id=short_id) return result.results[0] if result.results else None diff --git a/service/src/main/inse/patents/authors/profile.py b/service/src/main/inse/patents/authors/profile.py index 7c4ca646..93bd720f 100644 --- a/service/src/main/inse/patents/authors/profile.py +++ b/service/src/main/inse/patents/authors/profile.py @@ -93,7 +93,7 @@ def _author_topics(author: Author) -> list[AuthorTopic]: return topics[:15] -def _fetch_co_author_names(author_id: str, display_name: str) -> list[str]: +async 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() @@ -115,7 +115,7 @@ def _fetch_co_author_names(author_id: str, display_name: str) -> list[str]: } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) @@ -141,7 +141,7 @@ def _fetch_co_author_names(author_id: str, display_name: str) -> list[str]: return co_authors[:40] -def build_author_profile( +async def build_author_profile( author: Author, *, patent_hit_count: int | None = None, @@ -154,7 +154,7 @@ def build_author_profile( co_author_names: list[str] = [] if fetch_co_authors and author_id: - co_author_names = _fetch_co_author_names(author_id, display_name) + co_author_names = await _fetch_co_author_names(author_id, display_name) return AuthorProfile( author_id=author_id, diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index 44e8e2f0..f7b44677 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -315,7 +315,7 @@ async def _search_patents_by_author( 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) + profile = await 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] From ba86d417b41a27b4925776e6395dfa9c27ba53e3 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Mon, 29 Jun 2026 20:12:35 +0200 Subject: [PATCH 03/60] docs(org-patents): document index_org_patents script and add to service README --- service/README.md | 26 ++++++++++++ service/scripts/index_org_patents.py | 63 ++++++++++++++++++++++++++-- 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/service/README.md b/service/README.md index ca09165c..7b405ffd 100644 --- a/service/README.md +++ b/service/README.md @@ -15,3 +15,29 @@ This mounts the source directory into the container and enables uvicorn hot-relo ## Testing Run tests: `./gradlew :service:test` + +## Scripts + +### index_org_patents.py + +Builds the `org_patents` Elasticsearch index for a given institution. This pre-indexes +all patents linked to an institution (via institution assignee and author name matching) +so they can be browsed efficiently in the app. + +```bash +python scripts/index_org_patents.py --institution-id +``` + +**Example — University of Duisburg-Essen:** + +```bash +python scripts/index_org_patents.py --institution-id I62318514 +``` + +The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`. + +**Runtime:** ~10–30 minutes for large institutions (UDE has ~76,000 patents). +Re-running is safe — existing entries are replaced. + +**Note:** This script is intended to be integrated into an Admin Panel in a later sprint, +so that organisation admins can trigger the indexing as a background job via the UI. diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py index 7eb03cef..7e00bc23 100644 --- a/service/scripts/index_org_patents.py +++ b/service/scripts/index_org_patents.py @@ -1,5 +1,55 @@ #!/usr/bin/env python3 -"""Index org_patents for an institution.""" +""" +index_org_patents.py — Build the org_patents Elasticsearch index for one institution. + +What this script does +--------------------- +1. Fetches all authors affiliated with the given institution from OpenAlex. +2. Searches EPO and USPTO for patents assigned to the institution (institution match). +3. Searches EPO and USPTO for patents where an author's name appears as inventor (name match). +4. Merges both result sets, deduplicates, and assigns a match_type per patent: + - "institution" — found via the institution assignee field only + - "name" — found via author name matching only + - "both" — found by both methods (highest confidence) +5. Deletes any existing org_patents documents for this institution in Elasticsearch. +6. Bulk-indexes the new documents into the `org_patents` index. + +Usage +----- +Run from the smartguide/service directory: + + python scripts/index_org_patents.py --institution-id + +Example (University of Duisburg-Essen): + + python scripts/index_org_patents.py --institution-id I62318514 + +The OpenAlex institution ID can be found in the app URL when browsing an institution, +e.g. /institution/I62318514/overview → ID is I62318514. + +Prerequisites +------------- +- A .env file must exist at src/main/inse/.env with: + PATENT_ELASTICSEARCH_URL=... + PATENT_ELASTICSEARCH_API_KEY=... + OPENALEX_ELASTICSEARCH_URL=... (or equivalent, for author lookups) +- The EPO and USPTO Elasticsearch indices (epo_index_1.0, uspto_patents_3.0) must be reachable. + +Runtime +------- +For the University of Duisburg-Essen (~76,000 patents, ~500 authors) this takes +roughly 10–30 minutes depending on network speed and Elasticsearch performance. +Smaller institutions finish in a few minutes. + +Re-running the script is safe: existing documents for the institution are deleted +before the new ones are indexed (full re-index). + +Future plans +------------ +This script is intended to be integrated into an Admin Panel in a later sprint, +so that organisation admins can trigger the indexing as a background job via the UI. +For now it must be run manually on the server or locally with VPN access. +""" from __future__ import annotations import argparse @@ -22,16 +72,21 @@ logger = logging.getLogger(__name__) async def main() -> None: - parser = argparse.ArgumentParser(description="Index org_patents for an institution.") + parser = argparse.ArgumentParser( + description="Build the org_patents index for one institution.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Example: python scripts/index_org_patents.py --institution-id I62318514", + ) parser.add_argument( "--institution-id", required=True, - help="OpenAlex institution ID, e.g. I62318514", + help="OpenAlex institution ID, e.g. I62318514 (University of Duisburg-Essen)", ) args = parser.parse_args() + logger.info("Starting org_patents indexing for institution %s ...", args.institution_id) count = await index_org_patents_for_institution(args.institution_id) - logger.info("Finished indexing %d patents for institution %s", count, args.institution_id) + logger.info("Done. Indexed %d patents for institution %s.", count, args.institution_id) if __name__ == "__main__": From 65e428f4c2e635c0651fd4ad5d629dd7a1d2e014 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 1 Jul 2026 09:51:04 +0200 Subject: [PATCH 04/60] fix(patents): prevent slider handles from crossing and reduce server requests on drag --- webapp/src/app/modules/patents/patents.component.html | 5 +++-- webapp/src/app/modules/patents/patents.component.ts | 10 ++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 3e3a64c6..825ec922 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -56,7 +56,7 @@ [max]="maxYear" [value]="selectedStartYear" [style.z-index]="selectedStartYear >= selectedEndYear - 5 ? 4 : 2" - (input)="onStartYearInput($event)" + (change)="onStartYearInput($event)" aria-label="Startjahr" /> @@ -123,6 +123,7 @@ diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index c808f7f3..42e82d3b 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -14,13 +14,22 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; -<<<<<<< HEAD -======= import { IpcClassification } from '../../api'; ->>>>>>> origin/dev type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type ClassificationSystem = 'IPC' | 'CPC'; + +interface ClassificationCard { + key: string; + symbols: string[]; + system: ClassificationSystem; + levelLabel: string; + primaryDescription: string | null; + hierarchy: { label: string; value: string }[]; +} + +const DESCRIPTION_PREVIEW_LENGTH = 140; const MIN_YEAR = 1978; @Component({ @@ -66,6 +75,10 @@ export class PatentsComponent implements OnInit { private searchSubject = new Subject(); + showDetail = false; + selectedPatent: PatentEntry | null = null; + readonly expandedClassificationKeys = new Set(); + constructor() { this.searchSubject .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) @@ -199,6 +212,18 @@ export class PatentsComponent implements OnInit { this.router.navigate(['/patent', patent.patent_id]); } + selectPatent(patent: PatentEntry): void { + this.selectedPatent = patent; + this.showDetail = true; + this.expandedClassificationKeys.clear(); + } + + closeDetail(): void { + this.showDetail = false; + this.selectedPatent = null; + this.expandedClassificationKeys.clear(); + } + private updateQueryParams(): void { this.router.navigate([], { relativeTo: this.route, @@ -223,8 +248,6 @@ export class PatentsComponent implements OnInit { if (isNaN(parsed.getTime())) return date; return new Intl.DateTimeFormat('de-DE').format(parsed); } -<<<<<<< HEAD -======= getPublicationStageLabel(patent: PatentEntry): string | null { return patent.kind ?? patent.application_type ?? null; @@ -341,5 +364,4 @@ export class PatentsComponent implements OnInit { const first = text.split(/[;|]/)[0]?.trim() ?? text; return first === first.toUpperCase() ? first.charAt(0) + first.slice(1).toLowerCase() : first; } ->>>>>>> origin/dev } 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 caeb4ecb..14012a4f 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -2,16 +2,11 @@ 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'; -<<<<<<< HEAD import { MatchedPatentEntry } from '../../api/model/patentEntry'; import { formatPatentDate, getPublicationStageLabel, } from '../patent-detail/patent-detail.utils'; -======= -import { PatentEntry } from '../../api/model/patentEntry'; -import { IpcClassification } from '../../api'; ->>>>>>> origin/dev type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @@ -195,7 +190,6 @@ export class PersonPatentsComponent implements OnInit { return getPublicationStageLabel(patent); } -<<<<<<< HEAD formatMatchBadgeLabel(badge: string): string { const labels: Record = { Name: 'Name passt', @@ -203,137 +197,6 @@ export class PersonPatentsComponent implements OnInit { 'Co-Autor': 'Co-Autor passt', Thema: 'Themenbereich passt', Anmelder: 'Anmelder passt', -======= - hasPatentMetadata(_patent: PatentEntry): boolean { - return true; - } - - getPatentMetadataRows(patent: PatentEntry): PatentMetadataRow[] { - const rows: PatentMetadataRow[] = []; - - rows.push({ label: 'Quelle', value: patent.source, variant: 'source' }); - rows.push({ label: 'Patent-Nr.', value: patent.patent_id }); - - if (patent.publication_date) { - rows.push({ - label: 'Veröffentlichungsdatum', - value: this.formatDate(patent.publication_date), - }); - } - if (patent.application_number) { - rows.push({ - label: 'Anmeldungsnummer', - value: patent.application_number, - }); - } - if (patent.application_date) { - rows.push({ - label: 'Anmeldedatum', - value: this.formatDate(patent.application_date), - }); - } - - const stageLabel = this.getPublicationStageLabel(patent); - if (stageLabel) { - rows.push({ - label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', - value: patent.kind ? stageLabel : this.formatMetadataLabel(stageLabel), - }); - } - if (patent.number_of_claims != null) { - rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) }); - } - if (patent.status) { - rows.push({ - label: 'Status', - value: this.formatMetadataLabel(patent.status), - }); - } - - return rows; - } - - private formatMetadataLabel(value: string): string { - return value - .replace(/_/g, ' ') - .toLowerCase() - .replace(/\b\w/g, (char) => char.toUpperCase()); - } - - getClassificationCards( - entries: IpcClassification[] | undefined, - system: ClassificationSystem, - ): ClassificationCard[] { - if (!entries?.length) { - return []; - } - - const merged = new Map(); - - for (const entry of entries) { - const card = this.buildClassificationCard(entry, system); - const mergeKey = - card.primaryDescription?.toLocaleLowerCase('en') ?? - card.symbols[0] ?? - card.key; - - const existing = merged.get(mergeKey); - if (existing) { - for (const symbol of card.symbols) { - if (!existing.symbols.includes(symbol)) { - existing.symbols.push(symbol); - } - } - continue; - } - - merged.set(mergeKey, card); - } - - return [...merged.values()]; - } - - toggleClassificationExpanded(key: string): void { - if (this.expandedClassificationKeys.has(key)) { - this.expandedClassificationKeys.delete(key); - return; - } - this.expandedClassificationKeys.add(key); - } - - isClassificationExpanded(key: string): boolean { - return this.expandedClassificationKeys.has(key); - } - - isLongDescription(text: string | null): boolean { - return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH; - } - - getDescriptionPreview(text: string | null): string { - if (!text) { - return ''; - } - if (text.length <= DESCRIPTION_PREVIEW_LENGTH) { - return text; - } - return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`; - } - - private buildClassificationCard( - entry: IpcClassification, - system: ClassificationSystem, - ): ClassificationCard { - const level = this.getClassificationLevel(entry); - const primaryDescription = this.extractDescriptionText(entry[level.field]); - - return { - key: `${system}-${entry.symbol}`, - symbols: [entry.symbol], - system, - levelLabel: level.label, - primaryDescription, - hierarchy: this.buildHierarchyRows(entry, primaryDescription), ->>>>>>> origin/dev }; return labels[badge] ?? badge; } @@ -342,79 +205,6 @@ export class PersonPatentsComponent implements OnInit { if (this.isCommonName) { return 'Keine sicheren Patentzuordnungen gefunden. Bei häufigen oder einteiligen Namen werden nur Patente mit starkem Kontext angezeigt.'; } -<<<<<<< HEAD return 'Keine sicheren Patentzuordnungen gefunden.'; -======= - if (entry.main_group) { - return { label: 'Hauptgruppe', field: 'main_group' }; - } - if (entry.subclass) { - return { label: 'Unterklasse', field: 'subclass' }; - } - if (entry.section) { - return { label: 'Sektion', field: 'section' }; - } - return { label: 'Code', field: 'symbol' }; - } - - private buildHierarchyRows( - entry: IpcClassification, - primaryDescription: string | null, - ): { label: string; value: string }[] { - const rows: { label: string; value: string }[] = []; - const seen = new Set(); - - const addRow = (label: string, raw: string | null) => { - const value = this.extractDescriptionText(raw); - if (!value) { - return; - } - const normalized = value.toLocaleLowerCase('en'); - if ( - seen.has(normalized) || - normalized === primaryDescription?.toLocaleLowerCase('en') - ) { - return; - } - seen.add(normalized); - rows.push({ label, value }); - }; - if (entry.section) { - addRow('Sektion', entry.section); - } - if (entry.class) { - addRow('Klasse', entry.class); - } - if (entry.subclass) { - addRow('Unterklasse', entry.subclass); - } - - return rows; - } - - private extractDescriptionText( - value: string | null | undefined, - ): string | null { - if (!value?.trim()) { - return null; - } - - const text = value.includes(' - ') - ? value.split(' - ').slice(1).join(' - ').trim() - : value.trim(); - if (!text) { - return null; - } - - const firstSentence = text.split(/[;|]/)[0]?.trim() ?? text; - return this.normalizeDescriptionCase(firstSentence); - } - - private normalizeDescriptionCase(text: string): string { - if (text !== text.toUpperCase()) { - return text; - } - return text.charAt(0) + text.slice(1).toLowerCase(); ->>>>>>> origin/dev } } From eba78a080ef3c515cde8a3c5e2446a8dc1117e01 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 1 Jul 2026 10:22:47 +0200 Subject: [PATCH 06/60] Fix build errors from dev merge: remove duplicate AllPatentsResponse, fix IpcClassification import, add null safety for optional arrays in patent-detail template Co-Authored-By: Claude Sonnet 4.6 --- webapp/src/app/api/api/patents.service.ts | 8 ++------ .../institution-patents.component.ts | 2 +- .../patent-detail.component.html | 20 +++++++++---------- .../patent-detail/patent-detail.utils.ts | 3 ++- .../person-patents.component.html | 2 +- 5 files changed, 16 insertions(+), 19 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index b5120634..3ad51a73 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -15,13 +15,9 @@ import { PatentEntry } from '../model/patentEntry'; import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; import { OrgPatentsResponse, OrgPatentMatchTypeFilter } from '../model/orgPatentsResponse'; +import { AllPatentsResponse } from '../model/allPatentsResponse'; -export interface AllPatentsResponse { - total: number; - page: number; - size: number; - patents: PatentEntry[]; -} +export type { AllPatentsResponse }; type GetPatentsByAuthorOptions = { httpHeaderAccept?: 'application/json'; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 8dd4be9e..b52689e1 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -184,7 +184,7 @@ export class InstitutionPatentsComponent implements OnInit { return value === 'all' || value === 'institution' || value === 'name' || value === 'both'; } - formatDate(date: string | null): string { + formatDate(date: string | null | undefined): string { return formatPatentDate(date); } diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.html b/webapp/src/app/modules/patent-detail/patent-detail.component.html index ff86b654..cb156aa5 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.html +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.html @@ -60,17 +60,17 @@
groups - {{ patent.inventors.length }} + {{ patent.inventors?.length ?? 0 }} Erfinder
business - {{ patent.assignees.length }} + {{ patent.assignees?.length ?? 0 }} Anmelder
category - {{ patent.ipc.length + patent.cpc.length }} + {{ (patent.ipc?.length ?? 0) + (patent.cpc?.length ?? 0) }} Klassifikationen
@@ -92,7 +92,7 @@
engineering

Erfinder

- {{ patent.inventors.length }} + {{ patent.inventors?.length ?? 0 }}
@for (inventor of patent.inventors; track inventor) { @@ -103,12 +103,12 @@
- @if (patent.assignees.length > 0) { + @if (patent.assignees?.length) {
account_balance

Anmelder

- {{ patent.assignees.length }} + {{ patent.assignees?.length ?? 0 }}
@for (assignee of patent.assignees; track assignee) { @@ -120,7 +120,7 @@
} - @if (patent.ipc_descriptions.length > 0) { + @if (patent.ipc_descriptions?.length) {
label @@ -182,7 +182,7 @@ }
- } @else if (patent.ipc.length > 0) { + } @else if (patent.ipc?.length) {
label @@ -196,7 +196,7 @@
} - @if (patent.cpc_descriptions.length > 0) { + @if (patent.cpc_descriptions?.length) {
label @@ -258,7 +258,7 @@ }
- } @else if (patent.cpc.length > 0) { + } @else if (patent.cpc?.length) {
label diff --git a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts index f98338a5..ddbe2a36 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts @@ -1,4 +1,5 @@ -import { IpcClassification, PatentEntry } from '../../api/model/patentEntry'; +import { PatentEntry } from '../../api/model/patentEntry'; +import { IpcClassification } from '../../api/model/ipcClassification'; export type ClassificationSystem = 'IPC' | 'CPC'; 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 714044db..1e99fb5f 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -88,7 +88,7 @@ }
- @if (selectedPatent.match_badges?.length) { + @if (selectedPatent.match_badges.length) {
@for (badge of selectedPatent.match_badges; track badge) { {{ formatMatchBadgeLabel(badge) }} From b37718e792bde8b0c2f5d99b8706c989a901eb84 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 1 Jul 2026 10:25:32 +0200 Subject: [PATCH 07/60] Fix TS2345: coerce optional IpcClassification fields to null in addRow calls Co-Authored-By: Claude Sonnet 4.6 --- webapp/src/app/modules/patent-detail/patent-detail.utils.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts index ddbe2a36..064924d8 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts @@ -185,9 +185,9 @@ function buildHierarchyRows( rows.push({ label, value }); }; - addRow('Sektion', entry.section); - addRow('Klasse', entry.class); - addRow('Unterklasse', entry.subclass); + addRow('Sektion', entry.section ?? null); + addRow('Klasse', entry.class ?? null); + addRow('Unterklasse', entry.subclass ?? null); return rows; } From 171e87f5756726b71b8da2ee4c86f0d0987a70ff Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 1 Jul 2026 10:28:11 +0200 Subject: [PATCH 08/60] Fix merge conflict in main.py: keep dev auth/account routers, remove duplicate projects_router import Co-Authored-By: Claude Sonnet 4.6 --- service/src/main/inse/main.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 887be948..f0d864fa 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -32,17 +32,10 @@ from inse.persons.service import router as persons_service_router from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.news.service import router as news_service_router -<<<<<<< HEAD -from inse.projects.router import router as projects_router -======= -from inse.patents.service import router as patents_service_router - from inse.auth.router import router as auth_router from inse.account_management.router import router as account_management_router from inse.organization_management.router import router as organization_management_router - ->>>>>>> origin/dev from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts From 503377e3bc52ca337674d0e4fb808a88fbe53a58 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Wed, 1 Jul 2026 20:53:45 +0200 Subject: [PATCH 09/60] Resolve merge conflicts --- .../src/main/inse/middleware/etag_cache.py | 174 +++++----- .../inse/patents/elastic_search_client.py | 277 ---------------- service/src/main/inse/patents/logic.py | 307 ------------------ service/src/main/inse/patents/service.py | 64 ---- 4 files changed, 77 insertions(+), 745 deletions(-) diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 31246ab3..f8c4db71 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -1,97 +1,77 @@ -# middleware/etag_cache.py -import hashlib -import json -import time - -from starlette.middleware.base import BaseHTTPMiddleware -from starlette.requests import Request -from starlette.responses import Response - - -class ETagCacheMiddleware(BaseHTTPMiddleware): - def __init__(self, app, ttl: int = 60): - super().__init__(app) - self.ttl = ttl # timeout in seconds - self.cache: dict[str, dict] = {} # key → {body, etag, expires} - - def _cache_key(self, request: Request) -> str: - # Include query params and relevant headers in the key - return f"{request.url.path}?{request.url.query}" - - def _content_type(self, response: Response) -> str | None: - return response.headers.get("content-type") - - async def dispatch(self, request: Request, call_next): - if request.method != "GET": - return await call_next(request) - - if request.url.path.startswith(("/api/auth", "/api/accounts")): - return await call_next(request) - - if request.headers.get("authorization"): - return await call_next(request) - - key = self._cache_key(request) - entry = self.cache.get(key) - client_etag = request.headers.get("if-none-match") - - # Cache hit + not expired - if entry and time.time() < entry["expires"]: - if client_etag == entry["etag"]: -<<<<<<< HEAD - return Response( - status_code=entry["status_code"], - headers={"ETag": entry["etag"]}, - ) -======= - headers = {"ETag": entry["etag"]} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response(status_code=304, headers=headers) ->>>>>>> origin/dev - - # Client has stale ETag - return fresh cached body - headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response( - content=entry["body"], -<<<<<<< HEAD - status_code=entry["status_code"], - media_type="application/json", - headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} -======= - headers=headers, ->>>>>>> origin/dev - ) - - # Cache miss or expired → hit the actual route - response = await call_next(request) - body = b"".join([chunk async for chunk in response.body_iterator]) - etag = f'"{hashlib.md5(body).hexdigest()}"' - content_type = self._content_type(response) - -<<<<<<< HEAD - if response.status_code < 400: - self.cache[key] = { - "body": body, - "etag": etag, - "expires": time.time() + self.ttl, - "status_code": response.status_code, - } -======= - self.cache[key] = { - "body": body, - "etag": etag, - "expires": time.time() + self.ttl, - "content_type": content_type, - } - headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} - if content_type: - headers["Content-Type"] = content_type ->>>>>>> origin/dev - return Response( - content=body, - status_code=response.status_code, - headers=headers, - ) +# middleware/etag_cache.py +import hashlib +import json +import time + +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import Response + + +class ETagCacheMiddleware(BaseHTTPMiddleware): + def __init__(self, app, ttl: int = 60): + super().__init__(app) + self.ttl = ttl # timeout in seconds + self.cache: dict[str, dict] = {} # key → {body, etag, expires} + + def _cache_key(self, request: Request) -> str: + # Include query params and relevant headers in the key + return f"{request.url.path}?{request.url.query}" + + def _content_type(self, response: Response) -> str | None: + return response.headers.get("content-type") + + async def dispatch(self, request: Request, call_next): + if request.method != "GET": + return await call_next(request) + + if request.url.path.startswith(("/api/auth", "/api/accounts")): + return await call_next(request) + + if request.headers.get("authorization"): + return await call_next(request) + + key = self._cache_key(request) + entry = self.cache.get(key) + client_etag = request.headers.get("if-none-match") + + # Cache hit + not expired + if entry and time.time() < entry["expires"]: + if client_etag == entry["etag"]: + headers = {"ETag": entry["etag"]} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] + return Response(status_code=304, headers=headers) + + # Client has stale ETag - return fresh cached body + headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] + return Response( + content=entry["body"], + status_code=entry.get("status_code", 200), + headers=headers, + ) + + # Cache miss or expired → hit the actual route + response = await call_next(request) + body = b"".join([chunk async for chunk in response.body_iterator]) + etag = f'"{hashlib.md5(body).hexdigest()}"' + content_type = self._content_type(response) + + if response.status_code < 400: + self.cache[key] = { + "body": body, + "etag": etag, + "expires": time.time() + self.ttl, + "status_code": response.status_code, + "content_type": content_type, + } + headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} + if content_type: + headers["Content-Type"] = content_type + return Response( + content=body, + status_code=response.status_code, + headers=headers, + ) diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 56638124..840ac21e 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -1,279 +1,2 @@ -<<<<<<< HEAD """Backward-compatible re-exports.""" from inse.patents.search_client import * # noqa: F403 -======= -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - HTTP client for patent searches in EPO and USPTO Elasticsearch indices. -""" -from typing import Any -from inse.integrations import elasticsearch -from inse.model import ESCluster, ESIndex -import asyncio -from .. import config -from .name_matching import search_name_variants - -DEFAULT_SEARCH_SIZE = 100 - - -def _match_name_field(field: str, name: str) -> dict[str, Any]: - """Match a name field, including transliterated variants (Müller/Mueller).""" - variants = search_name_variants(name) - if len(variants) <= 1: - return {"match": {field: variants[0] if variants else name}} - return { - "bool": { - "should": [{"match": {field: variant}} for variant in variants], - "minimum_should_match": 1, - } - } - - -from inse.exceptions import MissingApiKeyError - - -class PatentSearchClient: - def __init__( - self, - api_key: str | None = None, - ): - self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key - - def _headers(self) -> dict[str, str]: - if not self.api_key: - raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") - return { - "Authorization": f"ApiKey {self.api_key}", - "Content-Type": "application/json", - } - - def epo_query_by_inventor( - self, - last_name: str, - first_name: str | None = None, - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - """Search EPO index: first AND last name in the SAME inventor entry.""" - if first_name: - 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), - ] - } - }, - } - } - else: - query = { - "nested": { - "path": "inventors_name_nested", - "query": _match_name_field("inventors_name_nested.inventor", last_name), - } - } - - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"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, - last_name: str, - first_name: str | None = None, - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - """Search USPTO index: first AND last name in the SAME inventor entry.""" - if first_name: - query = { - "nested": { - "path": "inventors", - "query": { - "bool": { - "must": [ - _match_name_field("inventors.name", last_name), - _match_name_field("inventors.name", first_name), - ] - } - }, - } - } - else: - query = { - "nested": { - "path": "inventors", - "query": _match_name_field("inventors.name", last_name), - } - } - - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"publication_date": {"order": "desc", "missing": "_last"}}, - "_doc", - ], - "_source": [ - "publication_number", - "country", - "publication_date", - "publication_year", - "application_number", - "application_date", - "application_type", - "title", - "abstract", - "inventors_names", - "assignees_orgs", - "ipcr", - "cpc", - "number_of_claims", - "status", - ], - "query": query, - } - - async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: - return await self._search(ESIndex.EPO_INDEX, payload) - - async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: - return await self._search(ESIndex.USPTO_INDEX, payload) - - async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE) - return response - - async def get_by_id_or_title( - self, - patent_id: str, - prefix: str, - title: str, - size: int = 1, - ) -> dict[str, Any]: - """Search EPO and USPTO by ID; fall back to match_phrase on title if no hits. - - Args: - patent_id: The raw document/publication number (e.g. "1234567", "US1234567A"). - prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO. - Both indices are always queried for the ID lookup. - title: Used only when the ID lookup returns zero hits. - size: Maximum number of results to return. - """ - epo_id_payload = self._epo_query_by_id(patent_id, size) - uspto_id_payload = self._uspto_query_by_id(patent_id, size) - - epo_result, uspto_result = await asyncio.gather( - self.search_epo(epo_id_payload), - self.search_uspto(uspto_id_payload), - ) - - epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0) - uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0) - - if epo_hits > 0 or uspto_hits > 0: - if prefix.upper() == "EP" and epo_hits > 0: - return epo_result - if prefix.upper() == "US" and uspto_hits > 0: - return uspto_result - return epo_result if epo_hits > 0 else uspto_result - - if prefix.upper() == "US": - payload = self._uspto_query_by_title(title, size) - return await self.search_uspto(payload) - - payload = self._epo_query_by_title(title, size) - return await self.search_epo(payload) - #query builders - - def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: - """Term query against doc_number; strips a leading 'EP' prefix if present.""" - raw_id = patent_id.upper().removeprefix("EP") - return { - "size": size, - "_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": {"term": {"doc_number": raw_id}}, - } - - def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: - """Term query against publication_number; tries the ID as-is.""" - return { - "size": size, - "track_total_hits": True, - "sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"], - "_source": [ - "publication_number", "country", "publication_date", - "publication_year", "application_number", "application_date", - "application_type", "title", "abstract", "inventors_names", - "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", - ], - "query": {"term": {"publication_number": patent_id}}, - } - - def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]: - """match_phrase fallback on title_en (and title_de as a should clause).""" - return { - "size": size, - "_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": { - "bool": { - "should": [ - {"match_phrase": {"title_en": title}}, - {"match_phrase": {"title_de": title}}, - {"match_phrase": {"title_fr": title}}, - ], - "minimum_should_match": 1, - } - }, - } - - def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]: - """match_phrase fallback on title.""" - return { - "size": size, - "_source": [ - "publication_number", "country", "publication_date", - "publication_year", "application_number", "application_date", - "application_type", "title", "abstract", "inventors_names", - "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", - ], - "query": {"match_phrase": {"title": title}}, - } ->>>>>>> origin/dev diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 55a3c68e..26e73984 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -7,7 +7,6 @@ from inse.patents.institutions.logic import ( get_patents_by_institution_id, ) -<<<<<<< HEAD __all__ = [ "_deduplicate_patents", "_filter_patents_by_institution", @@ -16,309 +15,3 @@ __all__ = [ "get_patents_by_author_id", "get_patents_by_institution_id", ] -======= - -from ..persons import logic as person_logic -from ..models.openalex.author import Author -from . import model -from inse.exceptions import MissingApiKeyError, ElasticsearchException -from .elastic_search_client import PatentSearchClient -from .elastic_search_all_patents_client import AllPatentsSearchClient -from .ipc_search_client import IpcSearchClient -from .ipc_lookup import extract_ipc_symbol -from .name_matching import name_matches - -logger = logging.getLogger(__name__) - - -async def get_patent( - patent_id: str, - title: str, - prefix: str, - client: PatentSearchClient | None = None, -) -> model.PatentEntry: - search_client = client or PatentSearchClient() - - data = await search_client.get_by_id_or_title( - patent_id=patent_id, - prefix=prefix, - title=title, - ) - - parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits - elements = parse(data) - - if not elements: - return None - return elements[0] - - -async def get_patents_by_author_id( - author_id: str, - client: PatentSearchClient | None = None, - ipc_client: IpcSearchClient | None = None, -) -> model.PatentsByAuthorResponse: - search_client = client or PatentSearchClient() - ipc_search_client = ipc_client or IpcSearchClient() - - author = await _get_author(author_id) - if not author: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=None, - patent_count=0, - patents=[], - ) - - author_name = author.display_name - last_name = _extract_last_name(author_name) - first_name = _extract_first_name(author_name) - - if not last_name: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=0, - patents=[], - ) - - epo_data, uspto_data = await _search_both_indices( - search_client, last_name, first_name - ) - - 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) - - all_patents = _deduplicate_patents(all_patents) - - await _enrich_patents_classifications(all_patents, ipc_search_client) - - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=len(all_patents), - patents=all_patents, - ) - - -async def _search_both_indices(client, last_name, first_name): - epo_result, uspto_result = await asyncio.gather( - client.search_epo(client.epo_query_by_inventor(last_name, first_name)), - client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)), - ) - return epo_result, uspto_result - - -def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_name") or [] - applicants = src.get("applicants_name") or [] - ipc = src.get("ipc") or [] - cpc = src.get("cpc") or [] - patents.append(model.PatentEntry( - patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", - source="EPO", - title=src.get("title_en") or src.get("title_de"), - abstract=src.get("abstract"), - publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, - publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, - application_number=src.get("application_number"), - application_date=src.get("application_filing_date"), - kind=src.get("kind"), - inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None], - assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None], - ipc=_to_classification_strings(ipc), - cpc=_to_classification_strings(cpc), - country=src.get("country", "EP"), - )) - return patents - - -def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_names") or [] - assignees = src.get("assignees_orgs") or [] - ipc = src.get("ipcr") or [] - cpc = src.get("cpc") or [] - patents.append(model.PatentEntry( - patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", - source="USPTO", - title=src.get("title"), - abstract=src.get("abstract"), - publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, - publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, - application_number=src.get("application_number"), - application_date=str(src.get("application_date")) if src.get("application_date") else None, - application_type=src.get("application_type"), - number_of_claims=src.get("number_of_claims"), - status=src.get("status"), - inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None], - assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None], - ipc=_to_classification_strings(ipc), - cpc=_to_classification_strings(cpc), - country=src.get("country", "US"), - )) - return patents - - -def _to_classification_strings(value) -> list[str]: - if not value: - return [] - items = value if isinstance(value, list) else [value] - return [str(item).strip() for item in items if item and str(item).strip()] - - -def _descriptions_for_raw_codes( - raw_codes: list[str], - resolved: dict[str, model.IpcClassification], -) -> list[model.IpcClassification]: - return [ - resolved[extract_ipc_symbol(raw)] - for raw in raw_codes - if extract_ipc_symbol(raw) in resolved - ] - - -async def _enrich_patents_classifications( - patents: list[model.PatentEntry], - ipc_client: IpcSearchClient, -) -> None: - symbols = list(dict.fromkeys( - extract_ipc_symbol(raw) - for patent in patents - for raw in (*patent.ipc, *patent.cpc) - )) - if not symbols: - return - - try: - resolved = await ipc_client.resolve_symbols(symbols) - except MissingApiKeyError: - logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") - return - except ElasticsearchException as exc: - logger.warning("Classification enrichment failed: %s", exc) - return - except Exception as exc: - logger.exception("Classification enrichment failed unexpectedly: %s", exc) - return - - for patent in patents: - patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved) - patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved) - - -def _filter_patents_by_name( - patents: list[model.PatentEntry], - first_name: str, - 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) - ] - - -def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]: - seen: set[tuple[str, str, str, str]] = set() - deduplicated: list[model.PatentEntry] = [] - - for patent in patents: - key = _patent_dedup_key(patent) - if key in seen: - continue - seen.add(key) - deduplicated.append(patent) - - return deduplicated - - -def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: - stage = patent.kind or patent.application_type or "" - return ( - patent.source, - patent.patent_id, - patent.publication_date or "", - stage, - ) - - -async def _get_author(author_id: str) -> Author | None: - short_id = author_id.replace("https://openalex.org/", "") - result = await 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 - - -async def get_all_patents( - page: int = 0, - size: int = 10, - search: str | None = None, - source: str | None = None, - sort_by: str = "date", - sort_direction: str = "desc", - client: PatentSearchClient | None = None, - ipc_client: IpcSearchClient | None = None, -) -> model.AllPatentsResponse: - all_patents_client = AllPatentsSearchClient() - ipc_search_client = ipc_client or IpcSearchClient() - - if source == "EPO": - epo_data = await all_patents_client.search_epo( - all_patents_client.epo_query(page, size, search, sort_direction) - ) - patents = _parse_epo_hits(epo_data) - total = epo_data.get("hits", {}).get("total", {}).get("value", 0) - - elif source == "USPTO": - uspto_data = await all_patents_client.search_uspto( - all_patents_client.uspto_query(page, size, search, sort_direction) - ) - patents = _parse_uspto_hits(uspto_data) - total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) - - else: - half = size // 2 - epo_data, uspto_data = await asyncio.gather( - all_patents_client.search_epo( - all_patents_client.epo_query(page, half, search, sort_direction) - ), - all_patents_client.search_uspto( - all_patents_client.uspto_query(page, half, search, sort_direction) - ), - ) - patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - total = ( - epo_data.get("hits", {}).get("total", {}).get("value", 0) + - uspto_data.get("hits", {}).get("total", {}).get("value", 0) - ) - - - await _enrich_patents_classifications(patents, ipc_search_client) - - return model.AllPatentsResponse( - total=total, - page=page, - size=size, - patents=patents, - ) ->>>>>>> origin/dev diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 7870dde0..3cd2f6d8 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -1,74 +1,10 @@ """Aggregates patent API routers.""" from fastapi import APIRouter -<<<<<<< HEAD -======= -from . import logic -from . import model -from typing import Annotated, Optional -from fastapi import Path -from fastapi import Query - -router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) ->>>>>>> origin/dev from inse.patents.all.service import router as all_patents_router from inse.patents.authors.service import router as author_patents_router from inse.patents.institutions.service import router as institution_patents_router -<<<<<<< HEAD router = author_patents_router patents_router = all_patents_router institution_patents_router = institution_patents_router -======= - -@router.get( - "/{author_id}/patents", - operation_id="getPatentsByAuthor", - summary="Get patents matched to an author by name.", -) -async def get_patents_by_author(author_id: str) -> model.PatentsByAuthorResponse: - return await logic.get_patents_by_author_id(author_id) - - -@patents_router.get( - "/patents/{identifier}", - operation_id="getPatentByIdOrTitle", - summary="Returns one publication by OpenAlex ID or DOI.", -) -async def get_patent_by_identifier( - identifier: Annotated[str, Path(description="")], - prefix: Annotated[ - Optional[str], Query(description="Application Prefix (EP or US)") - ] = "", - title: Annotated[ - Optional[str], - Query( - description="Do we want to fallback to title search if ID and DOI dont work?" - ), - ] = "", -) -> model.PatentEntry | None: - return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title) - - -@patents_router.get( - "/patents", - operation_id="getAllPatents", - summary="Get all patents with pagination and search.", -) -async def get_all_patents( - page: int = 0, - size: int = 10, - search: str | None = None, - source: str | None = None, - sort_by: str = "date", - sort_direction: str = "desc", -) -> model.AllPatentsResponse: - return await logic.get_all_patents( - page=page, - size=size, - search=search, - source=source, - sort_by=sort_by, - sort_direction=sort_direction, - ) ->>>>>>> origin/dev From 4a17157643ce5905f050181d3ba313203e2b5f87 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Wed, 1 Jul 2026 22:52:46 +0200 Subject: [PATCH 10/60] Remove patent disambiguation and keep name-only author matching. --- .../main/inse/patents/authors/filtering.py | 127 ------ .../src/main/inse/patents/authors/logic.py | 65 +-- .../inse/patents/authors/name_frequency.py | 124 ------ .../inse/patents/authors/name_matching.py | 32 ++ .../src/main/inse/patents/authors/profile.py | 194 --------- .../src/main/inse/patents/authors/scoring.py | 201 --------- .../patents/authors/test_disambiguation.py | 308 ------------- .../inse/patents/authors/topic_matching.py | 176 -------- service/src/main/inse/patents/common/model.py | 15 +- service/src/main/inse/patents/org/logic.py | 73 +--- webapp/src/app/api/model/patentEntry.ts | 9 - .../app/api/model/patentsByAuthorResponse.ts | 5 +- .../person-patents.component.html | 10 +- .../person-patents.component.ts | 404 +++++++++--------- 14 files changed, 237 insertions(+), 1506 deletions(-) delete mode 100644 service/src/main/inse/patents/authors/filtering.py delete mode 100644 service/src/main/inse/patents/authors/name_frequency.py delete mode 100644 service/src/main/inse/patents/authors/profile.py delete mode 100644 service/src/main/inse/patents/authors/scoring.py delete mode 100644 service/src/main/inse/patents/authors/test_disambiguation.py delete mode 100644 service/src/main/inse/patents/authors/topic_matching.py diff --git a/service/src/main/inse/patents/authors/filtering.py b/service/src/main/inse/patents/authors/filtering.py deleted file mode 100644 index e2fa0ebe..00000000 --- a/service/src/main/inse/patents/authors/filtering.py +++ /dev/null @@ -1,127 +0,0 @@ -"""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 07086c23..3bf7ddff 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -7,22 +7,13 @@ from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE -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.authors.name_matching import filter_patents_by_author_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 @@ -51,11 +42,7 @@ async def get_patents_by_author_id( ) 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: + if not author_name or not author_name.strip(): return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, @@ -76,32 +63,16 @@ 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 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) + matched_patents = filter_patents_by_author_name(all_patents, author_name) - profile = await 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, - ) + await enrich_patents_classifications(matched_patents, ipc_search_client) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, patent_count=len(matched_patents), - is_common_name=profile.is_common_name, patents=matched_patents, ) @@ -113,34 +84,6 @@ async def _search_both_indices(client, display_name: str): ) -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], - last_name: str, -) -> list[model.PatentEntry]: - return [ - patent - for patent in patents - if any( - tokens_equal(inventor_last_name(inventor), last_name, allow_initial=False) - for inventor in patent.inventors - ) - ] - - async def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") result = await person_logic.search_persons(author_id=short_id) diff --git a/service/src/main/inse/patents/authors/name_frequency.py b/service/src/main/inse/patents/authors/name_frequency.py deleted file mode 100644 index eb8df001..00000000 --- a/service/src/main/inse/patents/authors/name_frequency.py +++ /dev/null @@ -1,124 +0,0 @@ -"""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 39d1a90e..789edcfd 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -7,6 +7,7 @@ from inse.patents.authors.name_variants import ( parse_person_name, _initials_from_tokens, ) +from inse.patents.common import model from inse.patents.common.text_normalization import ( name_token_variants, normalize_name_part, @@ -210,6 +211,37 @@ def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool: return name_matches_person(inventor_name, last_name) +def inventor_last_name(inventor_name: str) -> str | None: + parsed = parse_inventor_name(inventor_name) + return parsed.last_name if parsed else None + + +def filter_patents_by_author_name( + patents: list[model.PatentEntry], + display_name: str, +) -> list[model.PatentEntry]: + parsed = parse_person_name(display_name) + if parsed and parsed.is_single_token: + last_name = parsed.last_name + return [ + patent + for patent in patents + if any( + tokens_equal(inventor_last_name(inventor), last_name, allow_initial=False) + for inventor in patent.inventors + ) + ] + + return [ + patent + for patent in patents + if any( + name_matches_person(inventor, display_name) + for inventor in patent.inventors + ) + ] + + def _family_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> bool: author_candidates = _family_name_candidates(author) inventor_candidates = _family_name_candidates(inventor) diff --git a/service/src/main/inse/patents/authors/profile.py b/service/src/main/inse/patents/authors/profile.py deleted file mode 100644 index 93bd720f..00000000 --- a/service/src/main/inse/patents/authors/profile.py +++ /dev/null @@ -1,194 +0,0 @@ -"""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] - - -async 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 = await 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] - - -async 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 = await _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 deleted file mode 100644 index 36b58186..00000000 --- a/service/src/main/inse/patents/authors/scoring.py +++ /dev/null @@ -1,201 +0,0 @@ -"""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/test_disambiguation.py b/service/src/main/inse/patents/authors/test_disambiguation.py deleted file mode 100644 index aa908728..00000000 --- a/service/src/main/inse/patents/authors/test_disambiguation.py +++ /dev/null @@ -1,308 +0,0 @@ -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 deleted file mode 100644 index 707c516c..00000000 --- a/service/src/main/inse/patents/authors/topic_matching.py +++ /dev/null @@ -1,176 +0,0 @@ -"""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 38351b50..b3cc97a4 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -1,5 +1,3 @@ -from typing import Literal - from pydantic import BaseModel, ConfigDict, Field @@ -36,22 +34,11 @@ 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 - is_common_name: bool = False - patents: list[MatchedPatentEntry] + patents: list[PatentEntry] class PatentsByInstitutionResponse(BaseModel): diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index f7b44677..ad77a79e 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -12,17 +12,13 @@ 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.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.authors.name_matching import filter_patents_by_author_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, ) @@ -45,59 +41,6 @@ ORG_PATENT_SEARCH_SIZE = 500 AUTHOR_SEARCH_CONCURRENCY = 8 -def _extract_last_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[-1] if parts else None - - -def _extract_first_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[0] if len(parts) > 1 else None - - -def _filter_patents_by_last_name( - patents: list[PatentEntry], - last_name: str, -) -> list[PatentEntry]: - return [ - patent - for patent in patents - if any( - 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 @@ -284,9 +227,7 @@ 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) - if not last_name: + if not author_name: return [] try: @@ -308,16 +249,8 @@ async def _search_patents_by_author( raise patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - 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 = await 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] + return filter_patents_by_author_name(patents, author_name) async def build_org_patents_for_institution( diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index dc764e01..5565ab9a 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -32,12 +32,3 @@ 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 225ec78a..622d3920 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -7,13 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { MatchedPatentEntry } from './patentEntry'; +import { PatentEntry } from './patentEntry'; export interface PatentsByAuthorResponse { author_id: string; author_name?: string | null; patent_count: number; - is_common_name?: boolean; - patents: Array; + 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 1e99fb5f..7441c071 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -88,14 +88,6 @@ }
- @if (selectedPatent.match_badges.length) { -
- @for (badge of selectedPatent.match_badges; track badge) { - {{ formatMatchBadgeLabel(badge) }} - } -
- } - @if (getAbstractPreview(selectedPatent.abstract); as abstractPreview) {

{{ abstractPreview }}

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

Patentübersicht

-

Nur sicher zugeordnete Patente dieser Person.

+

Patente mit passendem Erfindername.

{{ patents.length }} 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 14012a4f..1af39c0f 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,210 +1,194 @@ -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 { MatchedPatentEntry } from '../../api/model/patentEntry'; -import { - formatPatentDate, - getPublicationStageLabel, -} from '../patent-detail/patent-detail.utils'; - -type SortMode = 'date' | 'title'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; - -@Component({ - selector: 'app-person-patents', - imports: [CommonModule], - templateUrl: './person-patents.component.html', - styleUrl: './person-patents.component.scss', -}) -export class PersonPatentsComponent implements OnInit { - private route = inject(ActivatedRoute); - private router = inject(Router); - private patentsApi = inject(PatentsService); - - patents: MatchedPatentEntry[] = []; - filteredPatents: MatchedPatentEntry[] = []; - authorName: string | null = null; - isCommonName = false; - selectedPatent: MatchedPatentEntry | null = null; - - loading = true; - error = false; - - activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'date'; - - selectedPage = 1; - readonly pageSize = 10; - - ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; - - const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); - - if (this.isValidFilter(filterFromUrl)) { - this.activeFilter = filterFromUrl; - } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; - } - - if (authorId) { - this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ - next: (result) => { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.isCommonName = result.is_common_name ?? false; - this.applyFilter(); - this.loading = false; - }, - error: () => { - this.error = true; - this.loading = false; - }, - }); - } - }); - } - - setFilter(filter: SourceFilter): void { - this.activeFilter = filter; - this.selectedPage = 1; - this.selectedPatent = null; - this.applyFilter(); - this.updateQueryParams(); - } - - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; - this.applyFilter(); - this.updateQueryParams(); - } - - selectPatent(patent: MatchedPatentEntry): void { - this.selectedPatent = patent; - this.updateQueryParams(); - } - - openDetail(): void { - if (!this.selectedPatent) return; - this.router.navigate(['/patent', this.selectedPatent.patent_id]); - } - - private applyFilter(): void { - let patents = this.patents; - - if (this.activeFilter !== 'all') { - patents = patents.filter((p) => p.source === this.activeFilter); - } - - this.filteredPatents = this.sortPatents(patents); - } - - private sortPatents(patents: MatchedPatentEntry[]): MatchedPatentEntry[] { - return [...patents].sort((a, b) => { - if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); - } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); - }); - } - - private updateQueryParams(): void { - this.router.navigate([], { - relativeTo: this.route, - queryParams: { - filter: this.activeFilter, - sortBy: this.sortMode, - }, - queryParamsHandling: 'merge', - replaceUrl: true, - }); - } - - private isValidFilter(value: string | null): value is SourceFilter { - return value === 'all' || value === 'EPO' || value === 'USPTO'; - } - - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; - } - - getPagedPatents(): MatchedPatentEntry[] { - const start = (this.selectedPage - 1) * this.pageSize; - return this.filteredPatents.slice(start, start + this.pageSize); - } - - getPageCount(): number { - return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); - } - - hasPagination(): boolean { - return this.getPageCount() > 1; - } - - setPage(page: number): void { - this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); - this.updateQueryParams(); - } - - formatDate(date: string | null | undefined): string { - return formatPatentDate(date); - } - - getEpoCount(): number { - return this.patents.filter((p) => p.source === 'EPO').length; - } - - getUsptoCount(): number { - return this.patents.filter((p) => p.source === 'USPTO').length; - } - - trackPatent(_index: number, patent: MatchedPatentEntry): string { - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } - - getAbstractPreview(abstract: string | null | undefined): string | null { - if (!abstract?.trim()) { - return null; - } - const text = abstract.trim(); - if (text.length <= 160) { - return text; - } - return `${text.slice(0, 160).trimEnd()}…`; - } - - 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.'; - } -} +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 { + formatPatentDate, + getPublicationStageLabel, +} from '../patent-detail/patent-detail.utils'; + +type SortMode = 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-person-patents', + imports: [CommonModule], + templateUrl: './person-patents.component.html', + styleUrl: './person-patents.component.scss', +}) +export class PersonPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: PatentEntry[] = []; + filteredPatents: PatentEntry[] = []; + authorName: string | null = null; + selectedPatent: PatentEntry | null = null; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + sortMode: SortMode = 'date'; + + selectedPage = 1; + readonly pageSize = 10; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const authorId = params.get('id') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.applyFilter(); + this.updateQueryParams(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.applyFilter(); + this.updateQueryParams(); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent = patent; + this.updateQueryParams(); + } + + openDetail(): void { + if (!this.selectedPatent) return; + this.router.navigate(['/patent', this.selectedPatent.patent_id]); + } + + private applyFilter(): void { + let patents = this.patents; + + if (this.activeFilter !== 'all') { + patents = patents.filter((p) => p.source === this.activeFilter); + } + + this.filteredPatents = this.sortPatents(patents); + } + + private sortPatents(patents: PatentEntry[]): PatentEntry[] { + return [...patents].sort((a, b) => { + if (this.sortMode === 'date') { + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); + } + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); + }); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private isValidFilter(value: string | null): value is SourceFilter { + return value === 'all' || value === 'EPO' || value === 'USPTO'; + } + + private isValidSortMode(value: string | null): value is SortMode { + return value === 'date' || value === 'title'; + } + + getPagedPatents(): PatentEntry[] { + const start = (this.selectedPage - 1) * this.pageSize; + return this.filteredPatents.slice(start, start + this.pageSize); + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); + } + + hasPagination(): boolean { + return this.getPageCount() > 1; + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.updateQueryParams(); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } + + trackPatent(_index: number, patent: PatentEntry): string { + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); + } + + getAbstractPreview(abstract: string | null | undefined): string | null { + if (!abstract?.trim()) { + return null; + } + const text = abstract.trim(); + if (text.length <= 160) { + return text; + } + return `${text.slice(0, 160).trimEnd()}…`; + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + getEmptyMessage(): string { + return 'Keine Patente gefunden.'; + } +} From 6962b497717ef2178f65f4d55798fb9d485ff59a Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 2 Jul 2026 13:42:04 +0200 Subject: [PATCH 11/60] feat(patents): add identity signals for patent disambiguation Use name specificity, institution/assignee overlap and topic similarity to reduce false positives in inventor-based patent matching. Treat IPC/CPC similarity as a supporting signal instead of proof of identity. --- .../src/main/inse/patents/authors/identity.py | 138 +++++++ .../patents/authors/ipc_topic_matching.py | 191 +++++++++ .../src/main/inse/patents/authors/logic.py | 60 ++- .../inse/patents/authors/name_matching.py | 30 +- .../inse/patents/authors/test_identity.py | 51 +++ .../authors/test_ipc_topic_matching.py | 145 +++++++ .../inse/patents/authors/test_topic_filter.py | 256 ++++++++++++ .../main/inse/patents/authors/topic_filter.py | 221 ++++++++++ service/src/main/inse/patents/common/model.py | 14 +- service/src/main/inse/patents/org/logic.py | 35 +- .../main/inse/patents/test_name_matching.py | 1 + service/src/main/inse/persons/logic.py | 52 +++ webapp/src/app/api/model/patentEntry.ts | 9 + .../app/api/model/patentsByAuthorResponse.ts | 4 +- .../person-patents.component.ts | 388 +++++++++--------- 15 files changed, 1388 insertions(+), 207 deletions(-) create mode 100644 service/src/main/inse/patents/authors/identity.py create mode 100644 service/src/main/inse/patents/authors/ipc_topic_matching.py create mode 100644 service/src/main/inse/patents/authors/test_identity.py create mode 100644 service/src/main/inse/patents/authors/test_ipc_topic_matching.py create mode 100644 service/src/main/inse/patents/authors/test_topic_filter.py create mode 100644 service/src/main/inse/patents/authors/topic_filter.py diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py new file mode 100644 index 00000000..1de0f927 --- /dev/null +++ b/service/src/main/inse/patents/authors/identity.py @@ -0,0 +1,138 @@ +"""Identity signals used to decide whether a patent really belongs to a person. + +These are the *strong* signals (name specificity, institution/assignee overlap) +that distinguish one same-named person from another. Topic/IPC similarity is only +a supporting plausibility signal and lives in ``ipc_topic_matching``. +""" +from __future__ import annotations + +from inse.models.openalex.author import Author +from inse.patents.authors.name_matching import ( + first_name_match_kind_for_person, + name_matches_person, +) +from inse.patents.authors.name_variants import parse_person_name +from inse.patents.common import model +from inse.patents.institutions.name_matching import assignee_matches_institution_name + +# Ambiguity is derived purely from data that already exists in the project (the +# number of patent hits for the name and the number of same-named authors in the +# local OpenAlex index) — no external name database is used. +# +# Thresholds are starting values and should be validated against a handful of +# test persons. +PATENT_HIT_COUNT_THRESHOLD = 300 +OPENALEX_FULL_NAME_COUNT_THRESHOLD = 2 +OPENALEX_LAST_NAME_COUNT_THRESHOLD = 100 + + +def is_ambiguous_name( + display_name: str | None, + *, + patent_hit_count: int = 0, + openalex_full_name_count: int | None = None, + openalex_last_name_count: int | None = None, +) -> bool: + """Decide whether a name is ambiguous using only internal project data. + + A name is treated as ambiguous (and therefore handled strictly) when: + - it is a mononym / cannot be parsed into given + family name, or + - several authors in the local OpenAlex index share the exact name, or + - many authors in the local OpenAlex index share the family name, or + - the patent name search returns a very large number of hits. + + Ambiguous names need a strong identity signal (institution/assignee or a + full given-name match with a matching research field) before a patent is + attributed to the person. + """ + parsed = parse_person_name(display_name) + if parsed is None or parsed.is_single_token: + return True + + if ( + openalex_full_name_count is not None + and openalex_full_name_count >= OPENALEX_FULL_NAME_COUNT_THRESHOLD + ): + return True + + if ( + openalex_last_name_count is not None + and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD + ): + return True + + if patent_hit_count >= PATENT_HIT_COUNT_THRESHOLD: + return True + + return False + + +def author_institution_names(author: Author) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + + def _add(display_name: str | None) -> None: + if not display_name or not display_name.strip(): + return + key = display_name.casefold() + if key in seen: + return + seen.add(key) + names.append(display_name.strip()) + + for institution in author.last_known_institutions or []: + _add(getattr(institution, "display_name", None)) + + for affiliation in author.affiliations or []: + institution = getattr(affiliation, "institution", None) + if institution is not None: + _add(getattr(institution, "display_name", None)) + + return names + + +def patent_institution_match( + patent: model.PatentEntry, + institution_names: list[str], +) -> bool: + if not institution_names: + return False + for assignee in patent.assignees: + if not assignee: + continue + for institution_name in institution_names: + if assignee_matches_institution_name(assignee, institution_name): + return True + return False + + +def patent_personal_assignee_match( + patent: model.PatentEntry, + display_name: str, +) -> bool: + """True when the person themselves is listed as an applicant/assignee. + + Being the personal applicant of a patent is a strong identity signal + (organisation assignees like companies/universities will not match a + full person name). + """ + if not display_name or not display_name.strip(): + return False + for assignee in patent.assignees: + if assignee and name_matches_person(assignee, display_name): + return True + return False + + +def best_name_match_kind(patent: model.PatentEntry, display_name: str) -> str: + """Best given-name match across all inventors: 'full' > 'initial' > 'none'.""" + best = "none" + for inventor in patent.inventors: + if not inventor: + continue + kind = first_name_match_kind_for_person(inventor, display_name) + if kind == "full": + return "full" + if kind == "initial": + best = "initial" + return best diff --git a/service/src/main/inse/patents/authors/ipc_topic_matching.py b/service/src/main/inse/patents/authors/ipc_topic_matching.py new file mode 100644 index 00000000..2296ce03 --- /dev/null +++ b/service/src/main/inse/patents/authors/ipc_topic_matching.py @@ -0,0 +1,191 @@ +"""Semantic comparison of patent text and classifications with author OpenAlex topics.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +import numpy as np + +from inse.patents.common import model +from inse.util import get_model + +STRONG_SIMILARITY_THRESHOLD = 0.82 +WEAK_SIMILARITY_THRESHOLD = 0.78 +CONFLICT_SIMILARITY_THRESHOLD = 0.78 + +TopicMatchLevel = Literal["strong", "weak", "none"] + + +@dataclass(frozen=True) +class TopicMatchResult: + level: TopicMatchLevel + similarity: float + topic_conflict: bool + + +def author_topic_names(author) -> list[str]: + topics: list[tuple[str, float]] = [] + for topic in author.topics or []: + if not topic.display_name: + continue + topics.append((topic.display_name, float(topic.score or 0.0))) + topics.sort(key=lambda item: item[1], reverse=True) + return [name for name, _score in topics[:15]] + + +def _label_from_classification_field(field: str) -> str: + cleaned = field.strip() + if " - " in cleaned: + return cleaned.split(" - ", 1)[1].strip() + return cleaned + + +def classification_description_labels(patent: model.PatentEntry) -> list[str]: + labels: list[str] = [] + seen: set[str] = set() + + for classification in (*patent.ipc_descriptions, *patent.cpc_descriptions): + for field in ( + classification.section, + classification.ipc_class, + classification.subclass, + classification.main_group, + classification.subgroup, + ): + if not field: + continue + label = _label_from_classification_field(field) + key = label.casefold() + if not label or key in seen: + continue + seen.add(key) + labels.append(label) + + return labels + + +def patent_topic_text(patent: model.PatentEntry) -> str: + parts: list[str] = [] + + if patent.title and patent.title.strip(): + parts.append(patent.title.strip()) + + if patent.abstract and patent.abstract.strip(): + parts.append(patent.abstract.strip()) + + classification_labels = classification_description_labels(patent) + if classification_labels: + parts.append(f"IPC/CPC: {', '.join(classification_labels)}") + + return " ".join(parts) + + +def patent_has_topic_signal(patent: model.PatentEntry) -> bool: + return bool(patent_topic_text(patent).strip()) + + +def _encode_texts(texts: list[str]) -> np.ndarray: + if not texts: + return np.empty((0, 0)) + model_instance = get_model() + return model_instance.encode(texts, normalize_embeddings=True) + + +def _max_cosine_similarity(left: np.ndarray, right: np.ndarray) -> float: + if left.size == 0 or right.size == 0: + return 0.0 + if left.ndim == 1: + left = left.reshape(1, -1) + if right.ndim == 1: + right = right.reshape(1, -1) + return float(np.max(left @ right.T)) + + +def _match_level(similarity: float) -> TopicMatchLevel: + if similarity >= STRONG_SIMILARITY_THRESHOLD: + return "strong" + if similarity >= WEAK_SIMILARITY_THRESHOLD: + return "weak" + return "none" + + +def match_patent_to_topics( + patent: model.PatentEntry, + topic_names: list[str], + *, + patent_vector: np.ndarray | None = None, + topic_vectors: np.ndarray | None = None, +) -> TopicMatchResult: + if not topic_names: + return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + patent_text = patent_topic_text(patent) + if not patent_text: + return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + patent_embedding = patent_vector + if patent_embedding is None: + patent_embedding = _encode_texts([patent_text])[0] + + topic_embedding = topic_vectors + if topic_embedding is None: + topic_embedding = _encode_texts(topic_names) + + similarity = _max_cosine_similarity(patent_embedding, topic_embedding) + topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD + + return TopicMatchResult( + level=_match_level(similarity), + similarity=round(similarity, 3), + topic_conflict=topic_conflict, + ) + + +def match_patents_to_topics( + patents: list[model.PatentEntry], + topic_names: list[str], +) -> list[TopicMatchResult]: + if not patents: + return [] + if not topic_names: + return [ + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + for _patent in patents + ] + + patent_texts = [patent_topic_text(patent) for patent in patents] + texts_to_encode = [text for text in patent_texts if text] + if not texts_to_encode: + return [ + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + for _patent in patents + ] + + encoded = _encode_texts(texts_to_encode) + topic_vectors = _encode_texts(topic_names) + + encoded_by_text = { + text: encoded[index] + for index, text in enumerate(texts_to_encode) + } + + results: list[TopicMatchResult] = [] + for patent_text in patent_texts: + if not patent_text: + results.append( + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + ) + continue + similarity = _max_cosine_similarity( + encoded_by_text[patent_text], + topic_vectors, + ) + topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD + results.append( + TopicMatchResult( + level=_match_level(similarity), + similarity=round(similarity, 3), + topic_conflict=topic_conflict, + ) + ) + return results diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 3bf7ddff..00753674 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -7,7 +7,12 @@ from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE +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.topic_filter import ( + filter_patents_by_author_topics, + to_author_patent_entry, +) from inse.patents.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( @@ -65,15 +70,62 @@ async def get_patents_by_author_id( all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) all_patents = deduplicate_patents(all_patents) - matched_patents = filter_patents_by_author_name(all_patents, author_name) + patent_hit_count = len(all_patents) + name_matched = filter_patents_by_author_name(all_patents, author_name) - await enrich_patents_classifications(matched_patents, ipc_search_client) + if not name_matched: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + ) + + await enrich_patents_classifications(name_matched, ipc_search_client) + + # Ambiguity is derived only from existing project data: how many patents the + # name search returned and how many same-named authors exist in the local + # OpenAlex index. + full_name_count = await person_logic.count_authors_by_display_name(author_name) + is_ambiguous = is_ambiguous_name( + author_name, + patent_hit_count=patent_hit_count, + openalex_full_name_count=full_name_count, + ) + + # Only pay for the extra works aggregation when the author document has no + # topics of its own. + fallback_topics: list[str] = [] + if not (author.topics or []): + fallback_topics = await person_logic.get_topic_names_for_author(author_id) + + logger.info( + "Topic filtering for %s: ambiguous=%s (patent_hits=%d, openalex_same_name=%d), " + "%d author topics, %d fallback topics, %d name-matched patents", + author_name, + is_ambiguous, + patent_hit_count, + full_name_count, + len(author.topics or []), + len(fallback_topics), + len(name_matched), + ) + + # The sentence-transformer encoding is CPU-bound; run it off the event loop + # so it does not block other requests. + filtered_patents = await asyncio.to_thread( + filter_patents_by_author_topics, + name_matched, + author, + is_ambiguous=is_ambiguous, + fallback_topic_names=fallback_topics, + ) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, - patent_count=len(matched_patents), - patents=matched_patents, + patent_count=len(filtered_patents), + patents=[to_author_patent_entry(item) for item in filtered_patents], ) diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index 789edcfd..c849330d 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -1,5 +1,4 @@ """Inventor name normalization and matching.""" -import re from inse.patents.authors.name_variants import ( ParsedPersonName, @@ -239,6 +238,10 @@ def filter_patents_by_author_name( name_matches_person(inventor, display_name) for inventor in patent.inventors ) + or any( + name_matches_person(assignee, display_name) + for assignee in patent.assignees + ) ] @@ -265,13 +268,32 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> if not inventor.given_names: return False - primary = author.primary_given_name - if primary and any( - tokens_equal(primary, inventor_given, allow_initial=True) + # Accept immediately when at least one inventor given-name token matches + # one of the author's given names as a full token (not only initial), + # e.g. "Maria Schmidt" vs "Anna Maria Schmidt". + if any( + any( + tokens_equal(author_given, inventor_given, allow_initial=False) + for author_given in author.given_names + ) for inventor_given in inventor.given_names ): return True + inventor_tokens_full = [ + token for token in inventor.given_names + if _initial_letter(token) is None + ] + + # Prevent false positives like "Karem C Weber" for "Christian Weber": + # if inventor has full given-name tokens but none matches the author, + # we reject even if one initial overlaps. + if inventor_tokens_full: + return False + + # Initials-only inventor names (e.g. "C. Weber", "P. J. Marrón") + # are considered a match only when every initial maps to one of + # the author's given names. return all( any( tokens_equal(author_given, inventor_given, allow_initial=True) diff --git a/service/src/main/inse/patents/authors/test_identity.py b/service/src/main/inse/patents/authors/test_identity.py new file mode 100644 index 00000000..a4ac8a05 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_identity.py @@ -0,0 +1,51 @@ +from inse.patents.authors.identity import ( + OPENALEX_FULL_NAME_COUNT_THRESHOLD, + OPENALEX_LAST_NAME_COUNT_THRESHOLD, + PATENT_HIT_COUNT_THRESHOLD, + is_ambiguous_name, +) + + +def test_mononym_is_always_ambiguous() -> None: + assert is_ambiguous_name("Weber") is True + assert is_ambiguous_name("") is True + assert is_ambiguous_name(None) is True + + +def test_two_token_name_not_ambiguous_without_signals() -> None: + assert is_ambiguous_name("Pedro Marrón") is False + + +def test_full_name_collision_makes_name_ambiguous() -> None: + assert ( + is_ambiguous_name( + "Christian Weber", + openalex_full_name_count=OPENALEX_FULL_NAME_COUNT_THRESHOLD, + ) + is True + ) + # A single OpenAlex author with that exact name is not a collision. + assert ( + is_ambiguous_name("Christian Weber", openalex_full_name_count=1) is False + ) + + +def test_last_name_collision_makes_name_ambiguous() -> None: + assert ( + is_ambiguous_name( + "Christian Weber", + openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD, + ) + is True + ) + assert ( + is_ambiguous_name("Christian Weber", openalex_last_name_count=10) is False + ) + + +def test_many_patent_hits_make_name_ambiguous() -> None: + assert ( + is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD) + is True + ) + assert is_ambiguous_name("Christian Weber", patent_hit_count=5) is False diff --git a/service/src/main/inse/patents/authors/test_ipc_topic_matching.py b/service/src/main/inse/patents/authors/test_ipc_topic_matching.py new file mode 100644 index 00000000..60599cc5 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_ipc_topic_matching.py @@ -0,0 +1,145 @@ +import numpy as np +import pytest + +from inse.patents.authors import ipc_topic_matching +from inse.patents.authors.ipc_topic_matching import ( + CONFLICT_SIMILARITY_THRESHOLD, + STRONG_SIMILARITY_THRESHOLD, + WEAK_SIMILARITY_THRESHOLD, + classification_description_labels, + match_patents_to_topics, + patent_topic_text, +) +from inse.patents.common import model + + +def _cluster_vector(label: str) -> np.ndarray: + vectors = { + "medical": np.array([1.0, 0.0, 0.0]), + "automotive": np.array([0.0, 1.0, 0.0]), + "wireless": np.array([0.95, 0.05, 0.0]), + } + vector = vectors[label] + return vector / np.linalg.norm(vector) + + +def _label_text(text: str) -> str: + lowered = text.lower() + if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire", "rubber tread")): + return "automotive" + if any(word in lowered for word in ("medical", "cardiac", "heart", "atherosclerosis")): + return "medical" + if any(word in lowered for word in ("wireless", "sensor", "network")): + return "wireless" + return "medical" + + +@pytest.fixture(autouse=True) +def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: + def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: + return np.stack([_cluster_vector(_label_text(text)) for text in texts]) + + monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) + + +def _classification(**fields: str) -> model.IpcClassification: + return model.IpcClassification(symbol="A61B 5/00", **fields) + + +def _patent(**kwargs) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP1", + source="EPO", + **kwargs, + ) + + +def test_patent_topic_text_includes_title_abstract_and_classifications() -> None: + patent = _patent( + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Pneumatic vehicle tire in radial design with profiled tread.", + ipc_descriptions=[ + _classification( + section="B - Performing operations; transporting", + ipc_class="B60 - Vehicles in general", + main_group="B60C - Tyres; tyre inflation", + ) + ], + ) + text = patent_topic_text(patent) + assert "Vehicle pneumatic tyre" in text + assert "Pneumatic vehicle tire" in text + assert "IPC/CPC:" in text + assert "Tyres" in text + assert "Vehicles in general" in text + + +def test_classification_description_labels_extracts_readable_names() -> None: + patent = _patent( + ipc_descriptions=[ + _classification( + section="A - Human necessities", + ipc_class="A61 - Medical science", + main_group="A61B 5/00 - Measuring for diagnostic purposes", + ) + ] + ) + labels = classification_description_labels(patent) + assert "Human necessities" in labels + assert "Medical science" in labels + assert "Measuring for diagnostic purposes" in labels + + +def test_match_patents_to_topics_strong_for_related_domain() -> None: + patent = _patent( + title="Cardiac arrhythmia monitoring system", + abstract="Heart rhythm monitoring for coronary artery disease.", + ipc_descriptions=[ + _classification( + section="A - Human necessities", + ipc_class="A61 - Medical or veterinary science", + ) + ], + ) + results = match_patents_to_topics( + [patent], + ["Cardiac arrhythmia and coronary artery disease"], + ) + assert results[0].level == "strong" + assert results[0].similarity >= STRONG_SIMILARITY_THRESHOLD + assert not results[0].topic_conflict + + +def test_match_patents_to_topics_conflict_for_unrelated_domain() -> None: + patent = _patent( + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Automotive tire tread composition for pneumatic tyres.", + ipc_descriptions=[ + _classification( + section="B - Performing operations", + ipc_class="B60 - Vehicles", + main_group="B60C - Tyres", + ) + ], + ) + results = match_patents_to_topics( + [patent], + ["Cardiac arrhythmia and coronary artery disease"], + ) + assert results[0].topic_conflict + assert results[0].similarity < CONFLICT_SIMILARITY_THRESHOLD + + +def test_match_patents_without_author_topics_is_neutral() -> None: + patent = _patent( + title="Vehicle pneumatic tyre", + ipc_descriptions=[_classification(section="B60 - Vehicles")], + ) + results = match_patents_to_topics([patent], []) + assert results[0].level == "none" + assert not results[0].topic_conflict + + +def test_threshold_ordering() -> None: + assert CONFLICT_SIMILARITY_THRESHOLD <= WEAK_SIMILARITY_THRESHOLD + assert WEAK_SIMILARITY_THRESHOLD < STRONG_SIMILARITY_THRESHOLD diff --git a/service/src/main/inse/patents/authors/test_topic_filter.py b/service/src/main/inse/patents/authors/test_topic_filter.py new file mode 100644 index 00000000..bf8d79c0 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_topic_filter.py @@ -0,0 +1,256 @@ +import numpy as np +import pytest + +from inse.models.openalex.author import Author +from inse.models.openalex.dehydrated_institution import DehydratedInstitution +from inse.models.openalex.work_topic import WorkTopic +from inse.patents.authors import ipc_topic_matching +from inse.patents.authors.ipc_topic_matching import TopicMatchResult +from inse.patents.authors.topic_filter import ( + decide_patent, + filter_patents_by_author_topics, + to_author_patent_entry, +) +from inse.patents.common import model + + +def _cluster_vector(label: str) -> np.ndarray: + vectors = { + "medical": np.array([1.0, 0.0, 0.0]), + "automotive": np.array([0.0, 1.0, 0.0]), + } + vector = vectors[label] + return vector / np.linalg.norm(vector) + + +def _label_text(text: str) -> str: + lowered = text.lower() + if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire")): + return "automotive" + return "medical" + + +@pytest.fixture(autouse=True) +def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: + def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: + return np.stack([_cluster_vector(_label_text(text)) for text in texts]) + + monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) + + +def _author( + display_name: str, + *topics: str, + institutions: list[str] | None = None, +) -> Author: + return Author( + display_name=display_name, + topics=[ + WorkTopic(display_name=topic, score=1.0 - index * 0.1) + for index, topic in enumerate(topics) + ], + last_known_institutions=[ + DehydratedInstitution(display_name=name) + for name in (institutions or []) + ], + ) + + +def _tire_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Automotive tire tread composition for pneumatic tyres.", + inventors=inventors, + assignees=assignees or [], + ipc_descriptions=[ + model.IpcClassification(symbol="B60C", ipc_class="B60 - Vehicles and tyres") + ], + ) + + +def _medical_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP2", + source="EPO", + title="Cardiac arrhythmia monitoring system", + abstract="Heart rhythm monitoring for coronary artery disease.", + inventors=inventors, + assignees=assignees or [], + ipc_descriptions=[ + model.IpcClassification(symbol="A61B", ipc_class="A61 - Medical or veterinary science") + ], + ) + + +# --- rare names: lenient ------------------------------------------------------ + +def test_rare_name_conflict_rejected() -> None: + author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") + patents = [_tire_patent(inventors=["Uncommon, Xaver"])] + filtered = filter_patents_by_author_topics(patents, author) + assert filtered == [] + + +def test_rare_name_related_topic_kept() -> None: + author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Uncommon, Xaver"])] + filtered = filter_patents_by_author_topics(patents, author) + assert len(filtered) == 1 + assert filtered[0].decision == "keep" + + +# --- common names: strict ----------------------------------------------------- + +def test_common_name_full_name_and_strong_topic_kept() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert len(filtered) == 1 + assert filtered[0].decision == "keep" + + +def test_common_name_initial_only_rejected_even_with_strong_topic() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, C."])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert filtered == [] + + +def test_common_name_conflict_rejected_without_institution() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_tire_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert filtered == [] + + +def test_common_name_institution_match_wins_over_conflict() -> None: + author = _author( + "Christian Weber", + "Cardiac arrhythmia disorders", + institutions=["Boston University"], + ) + patents = [ + _tire_patent(inventors=["Weber, C."], assignees=["Boston University"]) + ] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert len(filtered) == 1 + assert filtered[0].institution_match + assert filtered[0].decision == "keep" + + +# --- personal applicant (assignee) ------------------------------------------- + +def test_personal_assignee_match_keeps_patent_via_name_filter() -> None: + from inse.patents.authors.name_matching import filter_patents_by_author_name + + display_name = "Pedro José Marrón" + patent = model.PatentEntry( + patent_id="EP2867692", + source="EPO", + title="Method for generating and using a map", + abstract="Indoor localization map for wireless sensor networks.", + inventors=["Someone Else"], + assignees=["Marrón, Pedro José, Dr."], + ipc_descriptions=[ + model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") + ], + ) + # Name filter keeps it because the person is the applicant. + assert filter_patents_by_author_name([patent], display_name) == [patent] + + +def test_personal_assignee_is_strong_identity_signal() -> None: + author = _author( + "Pedro José Marrón", + "Energy Efficient Wireless Sensor Networks", + ) + patent = model.PatentEntry( + patent_id="EP2867692", + source="EPO", + title="Method for generating and using a map", + abstract="Indoor localization map for wireless sensor networks.", + inventors=["Someone Else"], + assignees=["Marrón, Pedro José, Dr."], + ipc_descriptions=[ + model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") + ], + ) + filtered = filter_patents_by_author_topics([patent], author) + assert len(filtered) == 1 + assert filtered[0].personal_assignee_match + assert filtered[0].decision == "keep" + + +# --- fallback topics ---------------------------------------------------------- + +def test_fallback_topics_enable_conflict_detection() -> None: + author = _author("Xaver Uncommon") # no topics on author document + patents = [_tire_patent(inventors=["Uncommon, Xaver"])] + + without_fallback = filter_patents_by_author_topics(patents, author) + assert len(without_fallback) == 1 # cannot judge topic -> lenient keep + + with_fallback = filter_patents_by_author_topics( + patents, + author, + fallback_topic_names=["Cardiac arrhythmia disorders"], + ) + assert with_fallback == [] # fallback reveals the conflict + + +# --- decision unit tests ------------------------------------------------------ + +def _match(level: str, conflict: bool) -> TopicMatchResult: + return TopicMatchResult(level=level, similarity=0.9, topic_conflict=conflict) + + +def test_decide_common_requires_strong_identity() -> None: + assert decide_patent( + is_common=True, + name_match="full", + institution_match=False, + topic_match=_match("weak", False), + can_judge_topic=True, + ) == "reject" + + assert decide_patent( + is_common=True, + name_match="full", + institution_match=False, + topic_match=_match("strong", False), + can_judge_topic=True, + ) == "keep" + + +def test_decide_institution_always_keeps() -> None: + assert decide_patent( + is_common=True, + name_match="initial", + institution_match=True, + topic_match=_match("none", True), + can_judge_topic=True, + ) == "keep" + + +def test_decide_rare_without_topic_judgement_keeps() -> None: + assert decide_patent( + is_common=False, + name_match="initial", + institution_match=False, + topic_match=_match("none", False), + can_judge_topic=False, + ) == "weaken" + + +# --- response mapping --------------------------------------------------------- + +def test_to_author_patent_entry_exposes_topic_metadata() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author)[0] + entry = to_author_patent_entry(filtered) + assert entry.topic_match_level == "strong" + assert entry.topic_filter_decision == "keep" + assert entry.topic_similarity is not None diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py new file mode 100644 index 00000000..49787fd0 --- /dev/null +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -0,0 +1,221 @@ +"""Attribute name-matched patents to a person using identity + topic signals. + +Identity signals (institution/assignee match, full given-name match) decide +*whether the patent belongs to the person*. IPC/CPC topic similarity is only a +supporting plausibility signal. The gating is adaptive: + +- rare names: lenient (only clear topic conflicts are dropped) +- common names: strict (a strong identity signal is required) +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from inse.models.openalex.author import Author +from inse.patents.authors.identity import ( + author_institution_names, + best_name_match_kind, + patent_institution_match, + patent_personal_assignee_match, +) +from inse.patents.authors.ipc_topic_matching import ( + TopicMatchResult, + author_topic_names, + match_patents_to_topics, + patent_has_topic_signal, +) +from inse.patents.common import model + +TopicFilterDecision = Literal["keep", "weaken", "reject"] +NameMatchKind = Literal["full", "initial", "none"] + + +@dataclass(frozen=True) +class FilteredPatent: + patent: model.PatentEntry + topic_match: TopicMatchResult + decision: TopicFilterDecision + name_match: NameMatchKind + institution_match: bool + personal_assignee_match: bool = False + + +def decide_patent( + *, + is_common: bool, + name_match: NameMatchKind, + institution_match: bool, + topic_match: TopicMatchResult, + can_judge_topic: bool, + personal_assignee_match: bool = False, +) -> TopicFilterDecision: + topic_conflict = topic_match.topic_conflict if can_judge_topic else False + topic_strong = (topic_match.level == "strong") if can_judge_topic else False + + # Institution/assignee overlap or the person being the personal applicant + # are the strongest identity signals we have. + if institution_match or personal_assignee_match: + return "keep" + + if is_common: + # Common names need a strong identity signal. A full given-name match + # together with a clearly matching research field is the minimum. + if name_match == "full" and topic_strong: + return "keep" + return "reject" + + # Rare names: lenient. Only drop clear thematic conflicts. + if topic_conflict: + return "reject" + if topic_strong or name_match == "full": + return "keep" + return "weaken" + + +def resolve_topic_names( + author: Author, + fallback_topic_names: list[str] | None = None, +) -> list[str]: + topic_names = author_topic_names(author) + if topic_names: + return topic_names + if fallback_topic_names: + return [name for name in fallback_topic_names if name and name.strip()] + return [] + + +_NEUTRAL_TOPIC = TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + +def _needs_topic_judgement( + *, + is_common: bool, + name_match: NameMatchKind, + strong_identity: bool, + can_judge_topic: bool, +) -> bool: + # A strong identity signal already decides "keep" without the topic. + if strong_identity: + return False + if not can_judge_topic: + return False + if is_common: + # Common names are only rescued by (full name + strong topic); + # without a full name they are rejected regardless of topic. + return name_match == "full" + # Rare names always consult the topic (conflict / strong check). + return True + + +def filter_patents_by_author_topics( + patents: list[model.PatentEntry], + author: Author, + *, + is_ambiguous: bool = False, + fallback_topic_names: list[str] | None = None, +) -> list[FilteredPatent]: + topic_names = resolve_topic_names(author, fallback_topic_names) + common_name = is_ambiguous + institution_names = author_institution_names(author) + display_name = author.display_name or "" + has_author_topics = bool(topic_names) + + # Pre-compute the cheap identity signals so we only run the expensive + # sentence-transformer encoding for patents whose decision truly depends + # on the research topic. + signals = [] + patents_to_encode: list[model.PatentEntry] = [] + for patent in patents: + name_match = best_name_match_kind(patent, display_name) + 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 + can_judge_topic = has_author_topics and patent_has_topic_signal(patent) + + needs_topic = _needs_topic_judgement( + is_common=common_name, + name_match=name_match, + strong_identity=strong_identity, + can_judge_topic=can_judge_topic, + ) + if needs_topic: + patents_to_encode.append(patent) + signals.append( + (name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic) + ) + + topic_by_patent_id = {} + if patents_to_encode: + encoded_matches = match_patents_to_topics(patents_to_encode, topic_names) + topic_by_patent_id = { + id(patent): match + for patent, match in zip(patents_to_encode, encoded_matches) + } + + filtered: list[FilteredPatent] = [] + for patent, signal in zip(patents, signals): + name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic = signal + topic_match = topic_by_patent_id.get(id(patent), _NEUTRAL_TOPIC) if needs_topic else _NEUTRAL_TOPIC + + decision = decide_patent( + is_common=common_name, + name_match=name_match, + institution_match=institution_match, + personal_assignee_match=personal_assignee_match, + topic_match=topic_match, + can_judge_topic=can_judge_topic and needs_topic, + ) + if decision == "reject": + continue + filtered.append( + FilteredPatent( + patent=patent, + topic_match=topic_match, + decision=decision, + name_match=name_match, + institution_match=institution_match, + personal_assignee_match=personal_assignee_match, + ) + ) + + filtered.sort( + key=lambda item: ( + item.decision != "keep", + not (item.institution_match or item.personal_assignee_match), + -item.topic_match.similarity, + item.patent.publication_date or "", + ), + ) + return filtered + + +def to_author_patent_entry(filtered: FilteredPatent) -> model.AuthorPatentEntry: + return model.AuthorPatentEntry( + **filtered.patent.model_dump(), + topic_similarity=filtered.topic_match.similarity or None, + topic_match_level=_response_match_level(filtered), + topic_filter_decision=( + "keep" if filtered.decision == "keep" else "weaken" + ), + ) + + +def patent_from_filtered(entry: model.AuthorPatentEntry) -> model.PatentEntry: + return model.PatentEntry( + **entry.model_dump( + exclude={ + "topic_similarity", + "topic_match_level", + "topic_filter_decision", + } + ) + ) + + +def _response_match_level(filtered: FilteredPatent) -> model.TopicMatchLevel: + if filtered.decision == "keep": + return "strong" + if filtered.decision == "weaken": + return "weak" + return "unknown" diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index b3cc97a4..783f6189 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,21 @@ class PatentEntry(BaseModel): country: str | None = None +TopicMatchLevel = Literal["strong", "weak", "unknown"] +TopicFilterDecision = Literal["keep", "weaken"] + + +class AuthorPatentEntry(PatentEntry): + topic_similarity: float | None = None + topic_match_level: TopicMatchLevel | None = None + topic_filter_decision: TopicFilterDecision | None = None + + class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[PatentEntry] + patents: list[AuthorPatentEntry] class PatentsByInstitutionResponse(BaseModel): diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index ad77a79e..67f0175e 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -12,7 +12,9 @@ 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.identity import is_ambiguous_name from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.authors.topic_filter import filter_patents_by_author_topics from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.model import PatentEntry from inse.patents.common.parsing import ( @@ -225,6 +227,7 @@ def fetch_authors_for_institution(institution_id: str) -> list[Author]: async def _search_patents_by_author( author: Author, search_client: PatentSearchClient, + ipc_client: IpcSearchClient, ) -> list[PatentEntry]: author_name = author.display_name if not author_name: @@ -250,7 +253,35 @@ async def _search_patents_by_author( patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) patents = deduplicate_patents(patents) - return filter_patents_by_author_name(patents, author_name) + patent_hit_count = len(patents) + name_matched = filter_patents_by_author_name(patents, author_name) + if not name_matched: + return [] + + await enrich_patents_classifications(name_matched, ipc_client) + + from inse.persons import logic as person_logic + + # Ambiguity is derived only from existing project data. + full_name_count = await person_logic.count_authors_by_display_name(author_name) + is_ambiguous = is_ambiguous_name( + author_name, + patent_hit_count=patent_hit_count, + openalex_full_name_count=full_name_count, + ) + + fallback_topics: list[str] = [] + if not (author.topics or []) and author.id: + fallback_topics = await person_logic.get_topic_names_for_author(author.id) + + filtered = await asyncio.to_thread( + filter_patents_by_author_topics, + name_matched, + author, + is_ambiguous=is_ambiguous, + fallback_topic_names=fallback_topics, + ) + return [item.patent for item in filtered] async def build_org_patents_for_institution( @@ -288,7 +319,7 @@ async def build_org_patents_for_institution( async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]: async with semaphore: - patents = await _search_patents_by_author(author, patent_client) + patents = await _search_patents_by_author(author, patent_client, ipc_search_client) return author, patents author_results = await asyncio.gather( diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index 1c086842..92af655f 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -132,6 +132,7 @@ def test_first_name_match_kind() -> None: ("López, Juan", "Juan Carlos García López", True), ("Mohamed Ali Hassan", "Mohamed Ali Hassan", True), ("Ali Hassan", "Mohamed Ali Hassan", True), + ("Karem C Weber", "Christian Weber", False), ], ) def test_name_matches_person_multi_part( diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index baeded67..754f3fa1 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -153,6 +153,40 @@ async def search_persons( return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) +async def _count_authors(query: dict) -> int: + """Return the total number of authors matching a query (no documents fetched).""" + data = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query=query, + size=0, + track_total_hits=True, + ) + total = data.get("hits", {}).get("total", {}) + if isinstance(total, dict): + return int(total.get("value", 0)) + return int(total or 0) + + +async def count_authors_by_display_name(display_name: str) -> int: + """Count authors in the local OpenAlex index whose full name collides. + + Used purely as an internal ambiguity signal: a value >= 2 means at least one + other author shares the exact name. + """ + if not display_name or not display_name.strip(): + return 0 + query = {"match_phrase": {"display_name": display_name.strip()}} + return await _count_authors(query) + + +async def count_authors_by_last_name(last_name: str) -> int: + """Count authors in the local OpenAlex index sharing a family name.""" + if not last_name or not last_name.strip(): + return 0 + query = {"match": {"display_name": last_name.strip()}} + return await _count_authors(query) + + async def _fetch_author_display_name(author_id: str) -> Optional[str]: query = { @@ -249,6 +283,24 @@ async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics +async def get_topic_names_for_author(author_id: str) -> list[str]: + """Return the author's primary research topic names from the works aggregation. + + Used as a fallback when the author document has no populated ``topics`` field. + """ + short_id = author_id.replace("https://openalex.org/", "").strip() + try: + _works, topics = await _fetch_works_and_topics(short_id) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to fetch fallback topics for author %s: %s", short_id, exc) + return [] + return [ + topic["display_name"] + for topic in topics + if topic.get("display_name") + ] + + async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 5565ab9a..f7f2f2df 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -32,3 +32,12 @@ export interface PatentEntry { country?: string | null; } +export type TopicMatchLevel = 'strong' | 'weak' | 'unknown'; +export type TopicFilterDecision = 'keep' | 'weaken'; + +export interface AuthorPatentEntry extends PatentEntry { + topic_similarity?: number | null; + topic_match_level?: TopicMatchLevel | null; + topic_filter_decision?: TopicFilterDecision | null; +} + diff --git a/webapp/src/app/api/model/patentsByAuthorResponse.ts b/webapp/src/app/api/model/patentsByAuthorResponse.ts index 622d3920..70eef4bc 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -7,12 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { PatentEntry } from './patentEntry'; +import { AuthorPatentEntry } from './patentEntry'; export interface PatentsByAuthorResponse { author_id: string; author_name?: string | null; patent_count: number; - patents: Array; + patents: Array; } 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 1af39c0f..8d9b20c9 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,194 +1,194 @@ -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 { - formatPatentDate, - getPublicationStageLabel, -} from '../patent-detail/patent-detail.utils'; - -type SortMode = 'date' | 'title'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; - -@Component({ - selector: 'app-person-patents', - imports: [CommonModule], - templateUrl: './person-patents.component.html', - styleUrl: './person-patents.component.scss', -}) -export class PersonPatentsComponent implements OnInit { - private route = inject(ActivatedRoute); - private router = inject(Router); - private patentsApi = inject(PatentsService); - - patents: PatentEntry[] = []; - filteredPatents: PatentEntry[] = []; - authorName: string | null = null; - selectedPatent: PatentEntry | null = null; - - loading = true; - error = false; - - activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'date'; - - selectedPage = 1; - readonly pageSize = 10; - - ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; - - const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); - - if (this.isValidFilter(filterFromUrl)) { - this.activeFilter = filterFromUrl; - } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; - } - - if (authorId) { - this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ - next: (result) => { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.applyFilter(); - this.loading = false; - }, - error: () => { - this.error = true; - this.loading = false; - }, - }); - } - }); - } - - setFilter(filter: SourceFilter): void { - this.activeFilter = filter; - this.selectedPage = 1; - this.selectedPatent = null; - this.applyFilter(); - this.updateQueryParams(); - } - - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; - this.applyFilter(); - this.updateQueryParams(); - } - - selectPatent(patent: PatentEntry): void { - this.selectedPatent = patent; - this.updateQueryParams(); - } - - openDetail(): void { - if (!this.selectedPatent) return; - this.router.navigate(['/patent', this.selectedPatent.patent_id]); - } - - private applyFilter(): void { - let patents = this.patents; - - if (this.activeFilter !== 'all') { - patents = patents.filter((p) => p.source === this.activeFilter); - } - - this.filteredPatents = this.sortPatents(patents); - } - - private sortPatents(patents: PatentEntry[]): PatentEntry[] { - return [...patents].sort((a, b) => { - if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); - } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); - }); - } - - private updateQueryParams(): void { - this.router.navigate([], { - relativeTo: this.route, - queryParams: { - filter: this.activeFilter, - sortBy: this.sortMode, - }, - queryParamsHandling: 'merge', - replaceUrl: true, - }); - } - - private isValidFilter(value: string | null): value is SourceFilter { - return value === 'all' || value === 'EPO' || value === 'USPTO'; - } - - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; - } - - getPagedPatents(): PatentEntry[] { - const start = (this.selectedPage - 1) * this.pageSize; - return this.filteredPatents.slice(start, start + this.pageSize); - } - - getPageCount(): number { - return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); - } - - hasPagination(): boolean { - return this.getPageCount() > 1; - } - - setPage(page: number): void { - this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); - this.updateQueryParams(); - } - - formatDate(date: string | null | undefined): string { - return formatPatentDate(date); - } - - getEpoCount(): number { - return this.patents.filter((p) => p.source === 'EPO').length; - } - - getUsptoCount(): number { - return this.patents.filter((p) => p.source === 'USPTO').length; - } - - trackPatent(_index: number, patent: PatentEntry): string { - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } - - getAbstractPreview(abstract: string | null | undefined): string | null { - if (!abstract?.trim()) { - return null; - } - const text = abstract.trim(); - if (text.length <= 160) { - return text; - } - return `${text.slice(0, 160).trimEnd()}…`; - } - - getPublicationStageLabel(patent: PatentEntry): string | null { - return getPublicationStageLabel(patent); - } - - getEmptyMessage(): string { - return 'Keine Patente gefunden.'; - } -} +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 { AuthorPatentEntry } from '../../api/model/patentEntry'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../patent-detail/patent-detail.utils'; + +type SortMode = 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-person-patents', + imports: [CommonModule], + templateUrl: './person-patents.component.html', + styleUrl: './person-patents.component.scss', +}) +export class PersonPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: AuthorPatentEntry[] = []; + filteredPatents: AuthorPatentEntry[] = []; + authorName: string | null = null; + selectedPatent: AuthorPatentEntry | null = null; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + sortMode: SortMode = 'date'; + + selectedPage = 1; + readonly pageSize = 10; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const authorId = params.get('id') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.applyFilter(); + this.updateQueryParams(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.applyFilter(); + this.updateQueryParams(); + } + + selectPatent(patent: AuthorPatentEntry): void { + this.selectedPatent = patent; + this.updateQueryParams(); + } + + openDetail(): void { + if (!this.selectedPatent) return; + this.router.navigate(['/patent', this.selectedPatent.patent_id]); + } + + private applyFilter(): void { + let patents = this.patents; + + if (this.activeFilter !== 'all') { + patents = patents.filter((p) => p.source === this.activeFilter); + } + + this.filteredPatents = this.sortPatents(patents); + } + + private sortPatents(patents: AuthorPatentEntry[]): AuthorPatentEntry[] { + return [...patents].sort((a, b) => { + if (this.sortMode === 'date') { + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); + } + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); + }); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private isValidFilter(value: string | null): value is SourceFilter { + return value === 'all' || value === 'EPO' || value === 'USPTO'; + } + + private isValidSortMode(value: string | null): value is SortMode { + return value === 'date' || value === 'title'; + } + + getPagedPatents(): AuthorPatentEntry[] { + const start = (this.selectedPage - 1) * this.pageSize; + return this.filteredPatents.slice(start, start + this.pageSize); + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); + } + + hasPagination(): boolean { + return this.getPageCount() > 1; + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.updateQueryParams(); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } + + trackPatent(_index: number, patent: AuthorPatentEntry): string { + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); + } + + getAbstractPreview(abstract: string | null | undefined): string | null { + if (!abstract?.trim()) { + return null; + } + const text = abstract.trim(); + if (text.length <= 160) { + return text; + } + return `${text.slice(0, 160).trimEnd()}…`; + } + + getPublicationStageLabel(patent: AuthorPatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + getEmptyMessage(): string { + return 'Keine Patente gefunden.'; + } +} From c4e05a437655d9e6f75c2eea7054cb344b7effe8 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 5 Jul 2026 15:44:30 +0200 Subject: [PATCH 12/60] fix(patents): correct author-institution query and name-matching ambiguity checks for org_patents --- service/README.md | 15 +- service/scripts/index_org_patents.py | 48 +----- service/src/main/inse/model.py | 11 +- .../inse/patents/authors/name_matching.py | 12 +- .../inse/patents/common/text_normalization.py | 17 ++ .../main/inse/patents/institutions/logic.py | 2 +- .../patents/institutions/name_matching.py | 16 +- .../inse/patents/org/elastic_search_client.py | 156 ++++++++++++++++-- service/src/main/inse/patents/org/logic.py | 156 +++++++++--------- service/src/main/inse/patents/org/service.py | 47 +++++- 10 files changed, 334 insertions(+), 146 deletions(-) diff --git a/service/README.md b/service/README.md index 7b405ffd..25961c24 100644 --- a/service/README.md +++ b/service/README.md @@ -20,9 +20,12 @@ Run tests: `./gradlew :service:test` ### index_org_patents.py -Builds the `org_patents` Elasticsearch index for a given institution. This pre-indexes -all patents linked to an institution (via institution assignee and author name matching) -so they can be browsed efficiently in the app. +Builds the `org_patents` Elasticsearch index for a given institution: fetches its +OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee +and/or inventor name, and reindexes. Each patent is tagged with a `match_type` +(`institution`, `name`, or `both`, the latter being highest confidence). For common +inventor names, a name match is only kept if the assignee is the institution itself or +the person, to avoid pulling in unrelated patents via a shared name. ```bash python scripts/index_org_patents.py --institution-id @@ -36,8 +39,10 @@ python scripts/index_org_patents.py --institution-id I62318514 The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`. -**Runtime:** ~10–30 minutes for large institutions (UDE has ~76,000 patents). -Re-running is safe — existing entries are replaced. +**Runtime:** ~30–40 minutes for large institutions (author count is the main driver). +Re-running is safe — existing documents for the institution are deleted (via search + +`_bulk` delete-by-id, not `_delete_by_query`, which the patent-cluster API key rejects) +before reindexing, so stale documents don't linger. **Note:** This script is intended to be integrated into an Admin Panel in a later sprint, so that organisation admins can trigger the indexing as a background job via the UI. diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py index 7e00bc23..f315f2f9 100644 --- a/service/scripts/index_org_patents.py +++ b/service/scripts/index_org_patents.py @@ -2,53 +2,21 @@ """ index_org_patents.py — Build the org_patents Elasticsearch index for one institution. -What this script does ---------------------- -1. Fetches all authors affiliated with the given institution from OpenAlex. -2. Searches EPO and USPTO for patents assigned to the institution (institution match). -3. Searches EPO and USPTO for patents where an author's name appears as inventor (name match). -4. Merges both result sets, deduplicates, and assigns a match_type per patent: - - "institution" — found via the institution assignee field only - - "name" — found via author name matching only - - "both" — found by both methods (highest confidence) -5. Deletes any existing org_patents documents for this institution in Elasticsearch. -6. Bulk-indexes the new documents into the `org_patents` index. - -Usage ------ -Run from the smartguide/service directory: +Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for +patents matched via institution assignee and/or author name (match_type: "institution", +"name", or "both"), deletes existing documents for the institution, and reindexes. +Usage: python scripts/index_org_patents.py --institution-id Example (University of Duisburg-Essen): - python scripts/index_org_patents.py --institution-id I62318514 -The OpenAlex institution ID can be found in the app URL when browsing an institution, -e.g. /institution/I62318514/overview → ID is I62318514. +Requires src/main/inse/.env with PATENT_ELASTICSEARCH_URL/API_KEY (and OpenAlex ES +credentials for author lookup). Runtime scales with author count (~30-40 min for UDE's +4,740 authors). Re-running is safe: existing documents are deleted before reindexing. -Prerequisites -------------- -- A .env file must exist at src/main/inse/.env with: - PATENT_ELASTICSEARCH_URL=... - PATENT_ELASTICSEARCH_API_KEY=... - OPENALEX_ELASTICSEARCH_URL=... (or equivalent, for author lookups) -- The EPO and USPTO Elasticsearch indices (epo_index_1.0, uspto_patents_3.0) must be reachable. - -Runtime -------- -For the University of Duisburg-Essen (~76,000 patents, ~500 authors) this takes -roughly 10–30 minutes depending on network speed and Elasticsearch performance. -Smaller institutions finish in a few minutes. - -Re-running the script is safe: existing documents for the institution are deleted -before the new ones are indexed (full re-index). - -Future plans ------------- -This script is intended to be integrated into an Admin Panel in a later sprint, -so that organisation admins can trigger the indexing as a background job via the UI. -For now it must be run manually on the server or locally with VPN access. +Future: integrate into an Admin Panel so admins can trigger this via the UI. """ from __future__ import annotations diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 222d9603..40f009f1 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -5,7 +5,16 @@ This module defines the model classes returned from our api using pydantic. """ -from enum import StrEnum +import sys + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + from enum import Enum + + class StrEnum(str, Enum): + def __str__(self) -> str: + return self.value from pydantic import BaseModel from pydantic import Field diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index c849330d..384678e9 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -11,6 +11,7 @@ from inse.patents.common.text_normalization import ( name_token_variants, normalize_name_part, patent_transliteration_expansions, + strip_person_titles, ) @@ -132,7 +133,7 @@ def inventor_search_phrases(display_name: str) -> list[str]: 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) + inventor = parse_inventor_name(strip_person_titles(inventor_name)) if author is None or inventor is None: return False @@ -270,10 +271,17 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> # Accept immediately when at least one inventor given-name token matches # one of the author's given names as a full token (not only initial), - # e.g. "Maria Schmidt" vs "Anna Maria Schmidt". + # e.g. "Maria Schmidt" vs "Anna Maria Schmidt". This only counts if at + # least one side is a spelled-out name, not a bare initial — two + # coincidentally identical single-letter tokens (e.g. both just "K.") + # are far too weak a signal on their own and would otherwise match + # anyone sharing that one middle initial regardless of their actual + # first name (e.g. "Mahendra K. Sharma" incorrectly matching inventor + # "Vivek K." or "Virender K." on an unrelated patent). if any( any( tokens_equal(author_given, inventor_given, allow_initial=False) + and not (_initial_letter(author_given) and _initial_letter(inventor_given)) for author_given in author.given_names ) for inventor_given in inventor.given_names diff --git a/service/src/main/inse/patents/common/text_normalization.py b/service/src/main/inse/patents/common/text_normalization.py index a5f3f22b..06bac0ef 100644 --- a/service/src/main/inse/patents/common/text_normalization.py +++ b/service/src/main/inse/patents/common/text_normalization.py @@ -35,6 +35,23 @@ _PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = ( (r"a([lmnrt])", r"ae\1"), ) +# Titles that can appear before a person's name in patent inventor fields +_PERSON_TITLE_PATTERN = re.compile( + r"^\s*(?:" + r"Prof\.?|Dr\.?|Dipl\.?(?:-Ing\.?|-Math\.?|-Phys\.?|-Inform\.?)?|" + r"M\.Sc\.?|B\.Sc\.?|M\.Eng\.?|PhD\.?|Ing\.?|" + r"Prof\.?\s+Dr\.?|Dr\.?-Ing\.?|Dr\.?\s+rer\.?\s+nat\.?" + r")[.,]?\s+", + re.IGNORECASE, +) + + +def strip_person_titles(value: str | None) -> str: + """Remove academic/professional titles from the start of a person name string.""" + if not value: + return "" + return _PERSON_TITLE_PATTERN.sub("", value).strip() + def normalize_name_part(value: str | None) -> str: if not value: diff --git a/service/src/main/inse/patents/institutions/logic.py b/service/src/main/inse/patents/institutions/logic.py index e01ed75f..9575c38d 100644 --- a/service/src/main/inse/patents/institutions/logic.py +++ b/service/src/main/inse/patents/institutions/logic.py @@ -39,7 +39,7 @@ async def get_patents_by_institution_id( institution_client = institutions_client or InstitutionsSearchClient() short_id = institution_id.replace("https://openalex.org/", "") - institution = institution_client.get_institution_by_id(short_id) + institution = await institution_client.get_institution_by_id(short_id) search_names = _institution_search_names(institution) if not search_names: diff --git a/service/src/main/inse/patents/institutions/name_matching.py b/service/src/main/inse/patents/institutions/name_matching.py index bb5f1aba..132b85cb 100644 --- a/service/src/main/inse/patents/institutions/name_matching.py +++ b/service/src/main/inse/patents/institutions/name_matching.py @@ -57,9 +57,12 @@ def institution_search_variants(value: str | None) -> list[str]: def _significant_institution_tokens(text: str) -> set[str]: + # Normalize hyphens to spaces so "Duisburg-Essen" splits into "duisburg" + "essen", + # matching both hyphenated and space-separated forms in patent databases. + normalized = normalize_name_part(text).replace("-", " ") return { token - for token in normalize_name_part(text).split() + for token in normalized.split() if len(token) >= MIN_INSTITUTION_VARIANT_LEN and token not in _INSTITUTION_GENERIC_TOKENS } @@ -72,13 +75,16 @@ def assignee_matches_institution_name(assignee: str, institution_name: str) -> b return False original = institution_name.strip() - assignee_tokens = set(norm_assignee.split()) + # Normalize hyphens to spaces for consistent token splitting across patent databases + norm_assignee_flat = norm_assignee.replace("-", " ") + norm_name_flat = norm_name.replace("-", " ") + assignee_tokens = set(norm_assignee_flat.split()) if len(original) <= 6 and " " not in original: - return norm_name in assignee_tokens + return norm_name_flat in assignee_tokens - if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN: - if norm_name in norm_assignee or norm_assignee in norm_name: + if len(norm_name_flat) >= MIN_INSTITUTION_SUBSTRING_LEN: + if norm_name_flat in norm_assignee_flat or norm_assignee_flat in norm_name_flat: return True significant = _significant_institution_tokens(institution_name) diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py index c8ef2d8a..1f5761a3 100644 --- a/service/src/main/inse/patents/org/elastic_search_client.py +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -1,10 +1,13 @@ """HTTP client for the org_patents Elasticsearch index.""" import json import logging +from datetime import datetime from typing import Any import httpx +from inse.integrations import elasticsearch +from inse.models.openalex.author import Author from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry @@ -13,6 +16,91 @@ from inse import config logger = logging.getLogger(__name__) DEFAULT_PAGE_SIZE = 20 +OPENALEX_AUTHORS_INDEX = "openalex-authors" +AUTHOR_PAGE_SIZE = 500 + + +async def fetch_authors_by_institution_name(institution_name: str) -> list[Author]: + """Fetches OpenAlex authors currently affiliated with institution_name. + + Mirrors the persons/search-list default filter: last_known_institutions + must match AND there must be an affiliations entry for the same + institution from the current year or the year before. + """ + target_year = datetime.now().year - 1 + query = { + "bool": { + "filter": [ + { + "nested": { + "path": "last_known_institutions", + "query": { + "match_phrase": { + "last_known_institutions.display_name": institution_name, + } + }, + } + }, + { + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + { + "match_phrase": { + "affiliations.institution.display_name": institution_name, + } + }, + { + "range": { + "affiliations.years": {"gte": target_year}, + } + }, + ] + } + }, + } + }, + ] + } + } + sort = [ + {"works_count": {"order": "desc"}}, + {"id": {"order": "asc"}}, + ] + + authors: list[Author] = [] + search_after: list | None = None + + while True: + body: dict = { + "size": AUTHOR_PAGE_SIZE, + "query": query, + "sort": sort, + } + if search_after: + body["search_after"] = search_after + + response = await elasticsearch.search(index=OPENALEX_AUTHORS_INDEX, body=body) + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = dict(hit.get("_source", {})) + source["id"] = source.get("id") or hit.get("_id", "") + author = Author.from_dict(source) + if author: + authors.append(author) + + if len(hits) < AUTHOR_PAGE_SIZE: + break + search_after = hits[-1].get("sort") + if not search_after: + break + + return authors class OrgPatentsSearchClient: @@ -65,24 +153,66 @@ class OrgPatentsSearchClient: mapping_response.raise_for_status() async def delete_by_institution(self, institution_id: str) -> int: - payload = { - "query": {"term": {"institution_id": institution_id.upper()}}, - } + """Deletes all org_patents documents for institution_id. + + Uses a search + bulk-delete-by-id loop instead of _delete_by_query: + the patent-cluster API key has been observed to reject _delete_by_query + with 403 Forbidden, while individual document deletes via _bulk succeed. + """ + short_id = institution_id.upper() + query = {"term": {"institution_id": short_id}} + page_size = 1000 + deleted_total = 0 + async with httpx.AsyncClient( base_url=self.base_url, timeout=self.timeout, transport=self.transport, ) as client: - response = await client.post( - f"/{ORG_PATENTS_INDEX}/_delete_by_query", - headers=self._headers(), - json=payload, - params={"refresh": "true"}, - ) - if response.status_code == 404: - return 0 - response.raise_for_status() - return response.json().get("deleted", 0) + while True: + search_response = await client.post( + f"/{ORG_PATENTS_INDEX}/_search", + headers=self._headers(), + json={ + "size": page_size, + "query": query, + "_source": False, + "sort": ["_doc"], + }, + ) + if search_response.status_code == 404: + return deleted_total + search_response.raise_for_status() + hits = search_response.json().get("hits", {}).get("hits", []) + if not hits: + break + + bulk_lines = [ + json.dumps({"delete": {"_index": ORG_PATENTS_INDEX, "_id": hit["_id"]}}) + for hit in hits + ] + bulk_response = await client.post( + "/_bulk", + content="\n".join(bulk_lines) + "\n", + headers=self._headers("application/x-ndjson"), + params={"refresh": "true"}, + ) + bulk_response.raise_for_status() + result = bulk_response.json() + if result.get("errors"): + failed = [ + item + for item in result.get("items", []) + if item.get("delete", {}).get("status", 200) >= 400 + ] + logger.error("Bulk delete errors: %s", failed[:3]) + raise RuntimeError("Bulk deleting existing org_patents documents failed.") + + deleted_total += len(hits) + if len(hits) < page_size: + break + + return deleted_total async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None: if not documents: diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index 67f0175e..41a9d007 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -10,11 +10,14 @@ from starlette.status import HTTP_502_BAD_GATEWAY 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.identity import is_ambiguous_name +from inse.patents.authors.identity import ( + author_institution_names, + is_ambiguous_name, + patent_institution_match, + patent_personal_assignee_match, +) from inse.patents.authors.name_matching import filter_patents_by_author_name -from inse.patents.authors.topic_filter import filter_patents_by_author_topics from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.model import PatentEntry from inse.patents.common.parsing import ( @@ -26,7 +29,10 @@ from inse.patents.common.parsing import ( ) from inse.patents.institutions.logic import get_patents_by_institution_id from inse.patents.ipc_search_client import IpcSearchClient -from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.patents.org.elastic_search_client import ( + OrgPatentsSearchClient, + fetch_authors_by_institution_name, +) from inse.patents.org.model import ( MatchType, MatchTypeFilter, @@ -38,7 +44,6 @@ from inse.patents.search_client import PatentSearchClient logger = logging.getLogger(__name__) -AUTHOR_PAGE_SIZE = 500 ORG_PATENT_SEARCH_SIZE = 500 AUTHOR_SEARCH_CONCURRENCY = 8 @@ -76,6 +81,33 @@ def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchTy return "name" +def _canonical_authors_by_name( + author_patents: list[tuple[Author, list[PatentEntry]]], +) -> dict[str, Author]: + """Picks one Author per case-normalized display name to attribute matches to. + + OpenAlex sometimes merges multiple real people who share a name into a + single, noisy author record with a long, unrelated affiliation history + (e.g. an economist and a biochemist both named "Michael Ehrmann" ending up + under one ID with both "European Central Bank" and "University of X"). + Such merged records tend to have an inflated works_count and therefore + sort first in the author list, which would otherwise make them "win" the + dedup below. Preferring the author with the fewest total institutions + favors the cleaner, more specific identity for the drill-down link. + """ + canonical: dict[str, Author] = {} + for author, _ in author_patents: + name_key = (author.display_name or "").casefold().strip() + if not name_key: + continue + current_best = canonical.get(name_key) + if current_best is None or ( + len(author_institution_names(author)) < len(author_institution_names(current_best)) + ): + canonical[name_key] = author + return canonical + + def merge_org_patents( institution_id: str, institution_name: str | None, @@ -92,15 +124,25 @@ def merge_org_patents( else: entry.institution_match = True + canonical_authors = _canonical_authors_by_name(author_patents) + for author, patents in author_patents: author_id = normalize_author_id(author.id) author_name = author.display_name or "" if not author_id or not author_name: continue + # Use case-normalized name as dedup key to collapse OpenAlex duplicate records + # (e.g. "Kenji TANAKA" and "Kenji Tanaka" are the same person) + author_dedup_key = author_name.casefold().strip() or author_id + + # Attribute the match to the canonical (cleanest-profile) author for + # this name, not necessarily the one whose patents we're iterating — + # see _canonical_authors_by_name(). + canonical = canonical_authors.get(author_dedup_key, author) matched_author = MatchedAuthor( - openalex_author_id=author_id, - author_name=author_name, + openalex_author_id=normalize_author_id(canonical.id) or author_id, + author_name=canonical.display_name or author_name, ) for patent in patents: key = patent_dedup_key(patent) @@ -108,10 +150,10 @@ def merge_org_patents( if entry is None: accumulated[key] = _AccumulatedPatent( patent=patent, - matched_authors={author_id: matched_author}, + matched_authors={author_dedup_key: matched_author}, ) else: - entry.matched_authors[author_id] = matched_author + entry.matched_authors.setdefault(author_dedup_key, matched_author) org_patents: list[OrgPatentEntry] = [] short_institution_id = normalize_institution_id(institution_id) @@ -174,58 +216,9 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict: } -def fetch_authors_for_institution(institution_id: str) -> list[Author]: - short_id = normalize_institution_id(institution_id) - query = { - "nested": { - "path": "last_known_institutions", - "query": { - "term": { - "last_known_institutions.id": f"https://openalex.org/{short_id}", - } - }, - } - } - - authors: list[Author] = [] - search_after: list | None = None - sort = [ - {"works_count": {"order": "desc"}}, - {"id": {"order": "asc"}}, - ] - - while True: - body: dict = { - "size": AUTHOR_PAGE_SIZE, - "query": query, - "sort": sort, - } - if search_after: - body["search_after"] = search_after - - response = elasticsearch.search(index="openalex-authors", body=body) - hits = response.get("hits", {}).get("hits", []) - if not hits: - break - - for hit in hits: - source = dict(hit.get("_source", {})) - source["id"] = source.get("id") or hit.get("_id", "") - author = Author.from_dict(source) - if author: - authors.append(author) - - if len(hits) < AUTHOR_PAGE_SIZE: - break - search_after = hits[-1].get("sort") - if not search_after: - break - - return authors - - async def _search_patents_by_author( author: Author, + institution_name: str | None, search_client: PatentSearchClient, ipc_client: IpcSearchClient, ) -> list[PatentEntry]: @@ -258,30 +251,35 @@ async def _search_patents_by_author( if not name_matched: return [] - await enrich_patents_classifications(name_matched, ipc_client) - from inse.persons import logic as person_logic + from inse.patents.authors.name_variants import parse_person_name - # Ambiguity is derived only from existing project data. full_name_count = await person_logic.count_authors_by_display_name(author_name) + parsed_for_last = parse_person_name(author_name) + last_name_count: int | None = None + if parsed_for_last and not parsed_for_last.is_single_token: + last_name_count = await person_logic.count_authors_by_last_name( + parsed_for_last.last_name + ) is_ambiguous = is_ambiguous_name( author_name, patent_hit_count=patent_hit_count, openalex_full_name_count=full_name_count, + openalex_last_name_count=last_name_count, ) - fallback_topics: list[str] = [] - if not (author.topics or []) and author.id: - fallback_topics = await person_logic.get_topic_names_for_author(author.id) - - filtered = await asyncio.to_thread( - filter_patents_by_author_topics, - name_matched, - author, - is_ambiguous=is_ambiguous, - fallback_topic_names=fallback_topics, - ) - return [item.patent for item in filtered] + if is_ambiguous: + # Common names (Zhang, Li, Wang): only keep if the assignee matches the + # institution we're building this index for (not any institution from + # the author's whole affiliation history) or the person themselves. + inst_names = [institution_name] if institution_name else [] + return [ + p for p in name_matched + if patent_institution_match(p, inst_names) + or patent_personal_assignee_match(p, author_name) + ] + else: + return name_matched async def build_org_patents_for_institution( @@ -295,7 +293,7 @@ async def build_org_patents_for_institution( institution_client = institutions_client or InstitutionsSearchClient() short_id = normalize_institution_id(institution_id) - institution = institution_client.get_institution_by_id(short_id) + institution = await institution_client.get_institution_by_id(short_id) institution_name = institution.display_name institution_response = await get_patents_by_institution_id( @@ -306,7 +304,7 @@ async def build_org_patents_for_institution( ) institution_patents = institution_response.patents - authors = fetch_authors_for_institution(short_id) + authors = await fetch_authors_by_institution_name(institution_name) logger.info( "Building org_patents for %s (%s): %d authors, %d institution patents", institution_name, @@ -319,7 +317,9 @@ async def build_org_patents_for_institution( async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]: async with semaphore: - patents = await _search_patents_by_author(author, patent_client, ipc_search_client) + patents = await _search_patents_by_author( + author, institution_name, patent_client, ipc_search_client + ) return author, patents author_results = await asyncio.gather( @@ -395,7 +395,7 @@ async def get_org_patents_by_institution_id( institution_client = institutions_client or InstitutionsSearchClient() try: - institution = institution_client.get_institution_by_id(short_id) + institution = await institution_client.get_institution_by_id(short_id) institution_name = institution.display_name except Exception: institution_name = None diff --git a/service/src/main/inse/patents/org/service.py b/service/src/main/inse/patents/org/service.py index df04d86b..2db362c2 100644 --- a/service/src/main/inse/patents/org/service.py +++ b/service/src/main/inse/patents/org/service.py @@ -1,7 +1,9 @@ from functools import lru_cache from typing import Annotated -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query +from pydantic import BaseModel +from starlette.status import HTTP_202_ACCEPTED from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.patents.org import logic @@ -9,6 +11,8 @@ from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"]) +_rebuild_running: set[str] = set() + @lru_cache def get_institutions_search_client() -> InstitutionsSearchClient: @@ -42,3 +46,44 @@ async def get_org_patents_by_institution( source=source, institutions_client=client, ) + + +class RebuildResponse(BaseModel): + status: str + institution_id: str + message: str + + +@router.post( + "/{id}/org-patents/rebuild", + operation_id="rebuildOrgPatents", + response_model=RebuildResponse, + status_code=HTTP_202_ACCEPTED, + summary="Trigger a background rebuild of the org_patents index for an institution.", +) +async def rebuild_org_patents( + id: str, + background_tasks: BackgroundTasks, +) -> RebuildResponse: + short_id = logic.normalize_institution_id(id) + + if short_id in _rebuild_running: + raise HTTPException( + status_code=409, + detail=f"A rebuild for institution {short_id} is already in progress.", + ) + + async def _run() -> None: + _rebuild_running.add(short_id) + try: + await logic.index_org_patents_for_institution(short_id) + finally: + _rebuild_running.discard(short_id) + + background_tasks.add_task(_run) + + return RebuildResponse( + status="accepted", + institution_id=short_id, + message=f"Rebuild started for institution {short_id}. Check server logs for progress.", + ) From 40d8a5458d7f7fb65855a17ed911f5cd4b56489e Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 5 Jul 2026 21:15:59 +0200 Subject: [PATCH 13/60] fix(frontend/patents): update year-range display live while dragging, keep request on release --- .../src/app/modules/patents/patents.component.html | 2 ++ webapp/src/app/modules/patents/patents.component.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index da172f03..7f3b9e10 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -56,6 +56,7 @@ [max]="maxYear" [value]="selectedStartYear" [style.z-index]="selectedStartYear >= selectedEndYear - 5 ? 4 : 2" + (input)="onStartYearDrag($event)" (change)="onStartYearInput($event)" aria-label="Startjahr" />
diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index 42e82d3b..02572c61 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -121,6 +121,19 @@ export class PatentsComponent implements OnInit { return this.selectedStartYear !== this.minYear || this.selectedEndYear !== this.maxYear; } + // Fired continuously while dragging: only updates the displayed value/handle + // position, no HTTP request yet. + onStartYearDrag(event: Event): void { + const input = event.target as HTMLInputElement; + this.selectedStartYear = Math.min(parseInt(input.value, 10), this.selectedEndYear); + } + + onEndYearDrag(event: Event): void { + const input = event.target as HTMLInputElement; + this.selectedEndYear = Math.max(parseInt(input.value, 10), this.selectedStartYear); + } + + // Fired once on release: commits the value and triggers the search request. onStartYearInput(event: Event): void { const input = event.target as HTMLInputElement; this.selectedStartYear = Math.min(parseInt(input.value, 10), this.selectedEndYear); From de4ba0591eaaa3fec577f58af02005be2b1c49bd Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 6 Jul 2026 13:57:47 +0200 Subject: [PATCH 14/60] fix(patents): restore patent detail API and align frontend service types Re-add getPatentByIdOrTitle endpoint and OrgPatentMatchTypeFilter export lost during dev merge; update institution-patents to use options-based API. --- service/src/main/inse/patents/all/logic.py | 105 ++++++++++++++++++ service/src/main/inse/patents/all/service.py | 20 ++++ webapp/src/app/api/api/patents.service.ts | 19 +++- .../src/app/api/model/orgPatentsResponse.ts | 2 + .../institution-patents.component.ts | 14 +-- .../patent-detail/patent-detail.component.ts | 2 +- 6 files changed, 152 insertions(+), 10 deletions(-) diff --git a/service/src/main/inse/patents/all/logic.py b/service/src/main/inse/patents/all/logic.py index f18b6a8d..4c308c95 100644 --- a/service/src/main/inse/patents/all/logic.py +++ b/service/src/main/inse/patents/all/logic.py @@ -1,6 +1,7 @@ """Business logic for global patent listing.""" import asyncio from datetime import datetime + import httpx from fastapi import HTTPException from starlette.status import HTTP_404_NOT_FOUND @@ -83,3 +84,107 @@ async def get_all_patents( size=size, patents=patents, ) + + +def _normalize_patent_date(date_str: str) -> str: + return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d") + + +def _parse_patent_id(patent_id: str) -> tuple[str, str]: + normalized = patent_id.strip().upper() + if normalized.startswith("EP"): + return "EPO", normalized.removeprefix("EP") + if normalized.startswith("US"): + return "USPTO", normalized.removeprefix("US") + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Patent not found.", + ) + + +async def _search_by_id( + client: AllPatentsSearchClient, + patent_id: str, + filling_date: str | None = None, +) -> list[model.PatentEntry]: + try: + source, number = _parse_patent_id(patent_id) + except HTTPException: + return [] + + if source == "EPO": + data = await client.search_epo(client.epo_detail_query(number, filling_date)) + return parse_epo_hits(data) + data = await client.search_uspto(client.uspto_detail_query(number, filling_date)) + return parse_uspto_hits(data) + + +async def _search_by_title( + client: AllPatentsSearchClient, + title: str, + filling_date: str | None = None, + prefix: str | None = None, +) -> list[model.PatentEntry]: + if prefix and prefix.upper() == "US": + data = await client.search_uspto(client.uspto_title_query(title, filling_date)) + return parse_uspto_hits(data) + if prefix and prefix.upper() == "EP": + data = await client.search_epo(client.epo_title_query(title, filling_date)) + return parse_epo_hits(data) + + epo_data, uspto_data = await asyncio.gather( + client.search_epo(client.epo_title_query(title, filling_date)), + client.search_uspto(client.uspto_title_query(title, filling_date)), + ) + return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + + +async def get_patent_by_id( + patent_id: str, + prefix: str | None = None, + title: str | None = None, + filling_date: str | None = None, + ipc_client: IpcSearchClient | None = None, +) -> model.PatentEntry: + all_patents_client = AllPatentsSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + normalized_filling_date = ( + _normalize_patent_date(filling_date) if filling_date else None + ) + + lookup_id = patent_id + if prefix and not patent_id.upper().startswith(prefix.upper()): + lookup_id = f"{prefix.upper()}{patent_id}" + + try: + patents = await _search_by_id( + all_patents_client, lookup_id, normalized_filling_date + ) + + if not patents and title: + patents = await _search_by_title( + all_patents_client, + title, + normalized_filling_date, + prefix, + ) + + if not patents: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Patent not found.", + ) + + except MissingApiKeyError as exc: + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.", + ) from exc + except httpx.HTTPError as exc: + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.", + ) from exc + + await enrich_patents_classifications(patents[:1], ipc_search_client) + return patents[0] diff --git a/service/src/main/inse/patents/all/service.py b/service/src/main/inse/patents/all/service.py index a620c93c..2126fc29 100644 --- a/service/src/main/inse/patents/all/service.py +++ b/service/src/main/inse/patents/all/service.py @@ -33,3 +33,23 @@ async def get_all_patents( year_from=year_from, year_to=year_to, ) + + +@router.get( + "/patents/{identifier}", + operation_id="getPatentByIdOrTitle", + response_model=model.PatentEntry, + summary="Get a single patent by identifier with optional title fallback.", +) +async def get_patent_by_identifier( + identifier: str, + prefix: str | None = None, + title: str | None = None, + filling_date: str | None = None, +): + return await logic.get_patent_by_id( + patent_id=identifier, + prefix=prefix, + title=title, + filling_date=filling_date, + ) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 3ad51a73..14d602a1 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -368,12 +368,26 @@ export class PatentsService extends BaseService { } public getPatentById(patentId: string): Observable { + return this.getPatentByIdOrTitle(patentId); + } + + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + fillingDate?: string, + ): Observable { + let params = new HttpParams(); + if (prefix) params = params.set('prefix', prefix); + if (title) params = params.set('title', title); + if (fillingDate) params = params.set('filling_date', fillingDate); + const localVarHeaders = this.defaultHeaders; const { basePath, withCredentials } = this.configuration; const localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam( { - name: 'patentId', - value: patentId, + name: 'identifier', + value: identifier, in: 'path', style: 'simple', explode: false, @@ -383,6 +397,7 @@ export class PatentsService extends BaseService { )}`; return this.httpClient.get(`${basePath}${localVarPath}`, { + params, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, }); diff --git a/webapp/src/app/api/model/orgPatentsResponse.ts b/webapp/src/app/api/model/orgPatentsResponse.ts index 68b2be7a..1d085b3e 100644 --- a/webapp/src/app/api/model/orgPatentsResponse.ts +++ b/webapp/src/app/api/model/orgPatentsResponse.ts @@ -9,6 +9,8 @@ */ import { OrgPatentEntry } from './orgPatentEntry'; +export type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; + export interface OrgPatentsResponse { institution_id: string; institution_name?: string | null; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 2c807d97..2ff0c77c 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -130,13 +130,13 @@ export class InstitutionPatentsComponent implements OnInit { this.error = false; this.patentsApi - .getOrgPatentsByInstitution( - institutionId, - this.activeMatchType, - this.selectedPage - 1, - this.pageSize, - this.activeFilter !== 'all' ? this.activeFilter : undefined, - ) + .getOrgPatentsByInstitution(institutionId, 'body', false, { + matchType: + this.activeMatchType !== 'all' ? this.activeMatchType : undefined, + page: this.selectedPage - 1, + size: this.pageSize, + source: this.activeFilter !== 'all' ? this.activeFilter : undefined, + }) .subscribe({ next: (result) => { this.patents = result.patents ?? []; diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.ts b/webapp/src/app/modules/patent-detail/patent-detail.component.ts index 5052d8db..0394cc26 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.ts @@ -128,7 +128,7 @@ export class PatentDetailComponent implements OnInit { .getPatentByIdOrTitle(patentId, prefix, title, fillingDate) .pipe(finalize(() => (this.loading = false))) .subscribe({ - next: (patent) => { + next: (patent: PatentEntry) => { this.patent = patent; }, error: () => { From 9d6656b6c49ba813b959a720829037111c2a0bdb Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 6 Jul 2026 17:58:11 +0200 Subject: [PATCH 15/60] feat(patents): replace semantic filtering with IPC topic mapping --- service/scripts/build_ipc_openalex_mapping.py | 280 ++ service/scripts/check_author_patents.py | 78 + service/scripts/diagnose_author_patents.py | 94 + .../src/data/ipc_openalex_topic_mapping.json | 2962 +++++++++++++++++ .../src/main/inse/patents/authors/identity.py | 3 +- .../patents/authors/ipc_openalex_mapping.py | 405 +++ .../patents/authors/ipc_topic_matching.py | 191 -- .../src/main/inse/patents/authors/logic.py | 62 +- .../inse/patents/authors/name_matching.py | 27 +- .../authors/test_ipc_openalex_mapping.py | 155 + .../authors/test_ipc_topic_matching.py | 145 - .../inse/patents/authors/test_topic_filter.py | 256 -- .../main/inse/patents/authors/topic_filter.py | 261 +- service/src/main/inse/patents/common/model.py | 14 +- .../main/inse/patents/test_name_matching.py | 16 + service/src/main/inse/persons/logic.py | 18 - webapp/src/app/api/model/patentEntry.ts | 9 - .../app/api/model/patentsByAuthorResponse.ts | 4 +- webapp/src/app/app.routes.ts | 2 + .../person-patents.component.ts | 92 +- .../app/resolvers/person-patents.resolver.ts | 27 + 21 files changed, 4215 insertions(+), 886 deletions(-) create mode 100644 service/scripts/build_ipc_openalex_mapping.py create mode 100644 service/scripts/check_author_patents.py create mode 100644 service/scripts/diagnose_author_patents.py create mode 100644 service/src/data/ipc_openalex_topic_mapping.json create mode 100644 service/src/main/inse/patents/authors/ipc_openalex_mapping.py delete mode 100644 service/src/main/inse/patents/authors/ipc_topic_matching.py create mode 100644 service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py delete mode 100644 service/src/main/inse/patents/authors/test_ipc_topic_matching.py delete mode 100644 service/src/main/inse/patents/authors/test_topic_filter.py create mode 100644 webapp/src/app/resolvers/person-patents.resolver.ts diff --git a/service/scripts/build_ipc_openalex_mapping.py b/service/scripts/build_ipc_openalex_mapping.py new file mode 100644 index 00000000..2d6d43f6 --- /dev/null +++ b/service/scripts/build_ipc_openalex_mapping.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +""" +build_ipc_openalex_mapping.py — Build a 1:1 IPC/CPC → OpenAlex topic mapping file. + +Scans the `ipc` Elasticsearch index, matches each hierarchy level (section, class, +subclass, group, subgroup) to the closest OpenAlex topic from topic_hierarchy_cache.json, +and writes service/src/data/ipc_openalex_topic_mapping.json. + +Usage: + python scripts/build_ipc_openalex_mapping.py + python scripts/build_ipc_openalex_mapping.py --output ../src/data/ipc_openalex_topic_mapping.json + python scripts/build_ipc_openalex_mapping.py --min-score 0.35 + +Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials for the ipc index. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import re +import sys +from collections import defaultdict +from difflib import SequenceMatcher +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.integrations import elasticsearch # noqa: E402 +from inse.model import ESCluster # noqa: E402 +from inse.patents.ipc_search_client import IPC_INDEX # noqa: E402 + +logger = logging.getLogger(__name__) + +LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = ( + ("section", "cpc_section_number", "cpc_section_name"), + ("class", "cpc_class_number", "cpc_class_name"), + ("group", "cpc_group_number", "cpc_group_name"), + ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), +) +BUILD_LEVELS = ("section", "class", "subclass") + + +def _normalize_symbol(symbol: str | None) -> str: + if not symbol: + return "" + return symbol.strip().upper().replace(" ", "") + + +def _infer_subclass(symbol: str | None) -> str | None: + if not symbol: + return None + cleaned = _normalize_symbol(symbol) + match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned) + return match.group(1) if match else None + + +def _load_topic_cache() -> list[dict]: + cache_path = current_dir.parent / "src" / "data" / "topic_hierarchy_cache.json" + with cache_path.open(encoding="utf-8") as handle: + raw = json.load(handle) + topics = [] + for display_name, info in raw.items(): + topics.append( + { + "display_name": display_name, + "topic_id": info.get("topic_id"), + "subfield": info.get("subfield"), + "field": info.get("field"), + "domain": info.get("domain"), + } + ) + return topics + + +def _tokenize(text: str) -> set[str]: + return {token for token in re.findall(r"[a-z0-9]+", text.casefold()) if len(token) > 2} + + +def _prepare_topics(topics: list[dict]) -> tuple[list[dict], dict[str, set[int]]]: + prepared: list[dict] = [] + index: dict[str, set[int]] = defaultdict(set) + for idx, topic in enumerate(topics): + labels = [ + topic["display_name"], + topic.get("subfield"), + topic.get("field"), + topic.get("domain"), + ] + tokens: set[str] = set() + for label in labels: + if label: + tokens |= _tokenize(label) + prepared.append({**topic, "_tokens": tokens, "_labels": [l for l in labels if l]}) + for token in tokens: + index[token].add(idx) + return prepared, index + + +def _score_label(ipc_label: str, topic: dict) -> float: + ipc_text = ipc_label.casefold() + ipc_tokens = _tokenize(ipc_label) + best = 0.0 + for candidate in topic["_labels"]: + candidate_text = candidate.casefold() + ratio = SequenceMatcher(None, ipc_text, candidate_text).ratio() + token_overlap = len(ipc_tokens & topic["_tokens"]) + token_score = token_overlap / max(len(ipc_tokens), 1) + best = max(best, ratio, token_score) + return best + + +def _best_topic_match( + ipc_label: str, + topics: list[dict], + topic_index: dict[str, set[int]], + min_score: float, +) -> dict | None: + ipc_tokens = _tokenize(ipc_label) + candidate_indices: set[int] = set() + for token in ipc_tokens: + candidate_indices |= topic_index.get(token, set()) + if not candidate_indices: + return None + + best_topic = None + best_score = 0.0 + for idx in list(candidate_indices)[:100]: + topic = topics[idx] + score = _score_label(ipc_label, topic) + if score > best_score: + best_score = score + best_topic = topic + if best_topic is None or best_score < min_score: + return None + return { + "topic_id": best_topic["topic_id"], + "topic_display_name": best_topic["display_name"], + "subfield": best_topic.get("subfield"), + "field": best_topic.get("field"), + "domain": best_topic.get("domain"), + "match_score": round(best_score, 3), + } + + +async def _fetch_unique_ipc_entries() -> dict[str, dict[str, str]]: + entries: dict[str, dict[str, str]] = defaultdict(dict) + + async def _terms_with_label( + level: str, + number_field: str, + name_field: str, + size: int, + ) -> None: + for field_name in (number_field, f"{number_field}.keyword"): + payload = { + "size": 0, + "aggs": { + "items": { + "terms": {"field": field_name, "size": size}, + "aggs": { + "sample": { + "top_hits": {"size": 1, "_source": [name_field]}, + } + }, + } + }, + } + try: + data = await elasticsearch.search( + index=IPC_INDEX, + body=payload, + cluster=ESCluster.INSE, + ) + except Exception: + continue + buckets = data.get("aggregations", {}).get("items", {}).get("buckets", []) + if buckets: + break + else: + return + for bucket in buckets: + symbol = bucket.get("key") + hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) + if not symbol or not hits: + continue + name = hits[0].get("_source", {}).get(name_field) + if not name: + continue + normalized = _normalize_symbol(str(symbol)) + if level == "class" and len(normalized) != 3: + continue + if level == "subclass": + if len(normalized) <= 3: + continue + normalized = _infer_subclass(str(symbol)) or normalized + entries[level][normalized] = str(name).strip() + + if "section" in BUILD_LEVELS: + await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) + if "class" in BUILD_LEVELS: + await _terms_with_label("class", "cpc_class_number", "cpc_class_name", 500) + if "subclass" in BUILD_LEVELS: + await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000) + if "group" in BUILD_LEVELS: + await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) + if "subgroup" in BUILD_LEVELS: + await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) + return entries + + +def build_mapping(ipc_entries: dict[str, dict[str, str]], topics: list[dict], min_score: float) -> dict: + prepared_topics, topic_index = _prepare_topics(topics) + mapping = {level: {} for level in ("section", "class", "subclass", "group", "subgroup")} + label_cache: dict[tuple[str, str], dict | None] = {} + total = sum(len(symbols) for level, symbols in ipc_entries.items() if level in BUILD_LEVELS) + processed = 0 + + for level in BUILD_LEVELS: + symbols = ipc_entries.get(level, {}) + for symbol, label in symbols.items(): + processed += 1 + if processed % 500 == 0: + logger.info("Mapped %d / %d ipc symbols", processed, total) + cache_key = (level, label.casefold()) + if cache_key not in label_cache: + label_cache[cache_key] = _best_topic_match( + label, prepared_topics, topic_index, min_score + ) + match = label_cache[cache_key] + if match is None: + continue + mapping[level][symbol] = { + "topic_id": match["topic_id"], + "topic_display_name": match["topic_display_name"], + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "ipc_label": label, + "match_score": match["match_score"], + } + return mapping + + +async def main() -> None: + parser = argparse.ArgumentParser(description="Build IPC/CPC → OpenAlex topic mapping JSON.") + parser.add_argument( + "--output", + default=str(current_dir.parent / "src" / "data" / "ipc_openalex_topic_mapping.json"), + help="Output JSON path", + ) + parser.add_argument( + "--min-score", + type=float, + default=0.35, + help="Minimum label similarity score for a 1:1 assignment", + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + topics = _load_topic_cache() + logger.info("Loaded %d OpenAlex topics from cache", len(topics)) + + ipc_entries = await _fetch_unique_ipc_entries() + counts = {level: len(ipc_entries.get(level, {})) for level in BUILD_LEVELS} + logger.info("Fetched unique ipc symbols: %s", counts) + + mapping = build_mapping(ipc_entries, topics, args.min_score) + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(mapping, indent=2, ensure_ascii=True), encoding="utf-8") + + counts = {level: len(mapping[level]) for level in mapping} + logger.info("Wrote mapping to %s: %s", output_path, counts) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/scripts/check_author_patents.py b/service/scripts/check_author_patents.py new file mode 100644 index 00000000..2d6f37ac --- /dev/null +++ b/service/scripts/check_author_patents.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Quick check of patent counts for specific authors.""" +from __future__ import annotations + +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.authors.ipc_openalex_mapping import clear_mapping_cache +from inse.patents.authors.logic import get_patents_by_author_id +from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.authors.identity import is_ambiguous_name +from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.search_client import PatentSearchClient +from inse.persons import logic as person_logic + + +AUTHORS = [ + ("Dirk Schadendorf", "A5034365278", 8), + ("Christian Weber", "A5100603203", 14), +] + + +async def _counts(author_id: str) -> dict: + search_client = PatentSearchClient() + ipc_client = IpcSearchClient() + short_id = author_id.replace("https://openalex.org/", "") + person = await person_logic.search_persons(author_id=short_id) + author = person.results[0] if person.results else None + if not author or not author.display_name: + return {"error": "author not found"} + + epo_data, uspto_data = await asyncio.gather( + search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)), + search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)), + ) + all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + name_matched = filter_patents_by_author_name(all_patents, author.display_name) + await enrich_patents_classifications(name_matched, ipc_client) + full_name_count = await person_logic.count_authors_by_display_name(author.display_name) + ambiguous = is_ambiguous_name( + author.display_name, + patent_hit_count=len(all_patents), + openalex_full_name_count=full_name_count, + ) + filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous) + return { + "author_name": author.display_name, + "es_hits": len(all_patents), + "name_matched": len(name_matched), + "after_topic_filter": len(filtered), + "ambiguous": ambiguous, + "openalex_same_name": full_name_count, + "titles": [item.patent.title for item in filtered], + } + + +async def main() -> None: + clear_mapping_cache() + for label, author_id, expected in AUTHORS: + result = await _counts(author_id) + print(f"\n=== {label} ({author_id}) expected={expected} ===") + for key, value in result.items(): + if key == "titles": + print(f"{key}:") + for title in value: + print(f" - {title}") + else: + print(f"{key}: {value}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/scripts/diagnose_author_patents.py b/service/scripts/diagnose_author_patents.py new file mode 100644 index 00000000..bd8961cf --- /dev/null +++ b/service/scripts/diagnose_author_patents.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Per-patent breakdown of topic-filter decisions for test authors.""" +from __future__ import annotations + +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.authors.ipc_openalex_mapping import ( + clear_mapping_cache, + load_ipc_openalex_mapping, + patent_topics_match_author, + resolve_mapped_topics_for_patent, +) +from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.authors.identity import is_ambiguous_name, patent_institution_match, patent_personal_assignee_match +from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.search_client import PatentSearchClient +from inse.persons import logic as person_logic + +AUTHORS = [ + ("Dirk Schadendorf", "A5034365278"), + ("Christian Weber", "A5100603203"), +] + + +async def diagnose(author_id: str) -> None: + search_client = PatentSearchClient() + ipc_client = IpcSearchClient() + short_id = author_id.replace("https://openalex.org/", "") + person = await person_logic.search_persons(author_id=short_id) + author = person.results[0] + mapping = load_ipc_openalex_mapping() + + print(f"\n{'='*70}") + print(f"{author.display_name} ({author_id})") + print("Author topics:") + for t in author.topics or []: + print(f" - {t.display_name} ({t.id})") + + institutions = [] + for inst in author.last_known_institutions or []: + institutions.append(inst.display_name) + for aff in author.affiliations or []: + if aff.institution: + institutions.append(aff.institution.display_name) + print("Institutions:", institutions) + + epo_data, uspto_data = await asyncio.gather( + search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)), + search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)), + ) + all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + name_matched = filter_patents_by_author_name(all_patents, author.display_name) + await enrich_patents_classifications(name_matched, ipc_client) + full_name_count = await person_logic.count_authors_by_display_name(author.display_name) + ambiguous = is_ambiguous_name( + author.display_name, + patent_hit_count=len(all_patents), + openalex_full_name_count=full_name_count, + ) + print(f"ambiguous={ambiguous}, name_matched={len(name_matched)}") + + filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous) + kept_ids = {item.patent.patent_id for item in filtered} + + for i, patent in enumerate(name_matched, 1): + mapped = resolve_mapped_topics_for_patent(patent, mapping) + topic_match = patent_topics_match_author(patent, author, mapping) + inst_match = patent_institution_match(patent, institutions) + pers_match = patent_personal_assignee_match(patent, author.display_name or "") + kept = patent.patent_id in kept_ids + mapped_labels = [m.topic_display_name or m.topic_id for m in mapped] + ipc = patent.ipc[:3] if patent.ipc else [] + cpc = patent.cpc[:2] if patent.cpc else [] + print(f"\n[{i}] {'KEEP' if kept else 'DROP'} | {patent.title[:70] if patent.title else '?'}") + print(f" ipc={ipc} cpc={cpc}") + print(f" mapped={mapped_labels or 'NONE'}") + print(f" topic_match={topic_match} inst={inst_match} personal={pers_match}") + + +async def main() -> None: + clear_mapping_cache() + for label, author_id in AUTHORS: + await diagnose(author_id) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/src/data/ipc_openalex_topic_mapping.json b/service/src/data/ipc_openalex_topic_mapping.json new file mode 100644 index 00000000..0d405a23 --- /dev/null +++ b/service/src/data/ipc_openalex_topic_mapping.json @@ -0,0 +1,2962 @@ +{ + "section": { + "C": { + "topic_id": "https://openalex.org/T14184", + "topic_display_name": "Metallurgy and Material Science", + "ipc_label": "CHEMISTRY; METALLURGY", + "match_score": 1.0 + }, + "D": { + "topic_id": "https://openalex.org/T12514", + "topic_display_name": "Fashion and Cultural Textiles", + "ipc_label": "TEXTILES; PAPER", + "match_score": 0.5 + }, + "E": { + "topic_id": "https://openalex.org/T11777", + "topic_display_name": "Fixed Point Theorems Analysis", + "ipc_label": "FIXED CONSTRUCTIONS", + "match_score": 0.5 + }, + "F": { + "topic_id": "https://openalex.org/T12907", + "topic_display_name": "Mechanical Engineering and Vibrations Research", + "ipc_label": "MECHANICAL ENGINEERING; LIGHTING; HEATING; WEAPONS; BLASTING", + "match_score": 0.604 + }, + "G": { + "topic_id": "https://openalex.org/T12836", + "topic_display_name": "History and Developments in Astronomy", + "ipc_label": "PHYSICS", + "match_score": 1.0 + }, + "H": { + "topic_id": "https://openalex.org/T13429", + "topic_display_name": "Electricity Theft Detection Techniques", + "ipc_label": "ELECTRICITY", + "match_score": 1.0 + }, + "A": { + "topic_id": "https://openalex.org/T13694", + "topic_display_name": "Immigration Law and Human Rights", + "ipc_label": "HUMAN NECESSITIES", + "match_score": 0.6 + }, + "B": { + "topic_id": "https://openalex.org/T12659", + "topic_display_name": "Innovation Diffusion and Forecasting", + "ipc_label": "PERFORMING OPERATIONS; TRANSPORTING", + "match_score": 0.507 + } + }, + "class": { + "A01D": { + "topic_id": "https://openalex.org/T13896", + "topic_display_name": "Health Services Management and Policy", + "ipc_label": "HARVESTINGMOWING", + "match_score": 0.412 + }, + "A01H": { + "topic_id": "https://openalex.org/T10442", + "topic_display_name": "Knee injuries and reconstruction techniques", + "ipc_label": "NEW PLANTS OR NON-TRANSGENIC PROCESSES FOR OBTAINING THEMPLANT REPRODUCTION BY TISSUE CULTURE TECHNIQUES", + "match_score": 0.435 + }, + "A01J": { + "topic_id": "https://openalex.org/T11386", + "topic_display_name": "Bee Products Chemical Analysis", + "ipc_label": "MANUFACTURE OF DAIRY PRODUCTS for chemical matters, see subclass A23C", + "match_score": 0.465 + }, + "A01L": { + "topic_id": "https://openalex.org/T11905", + "topic_display_name": "Veterinary Pharmacology and Anesthesia", + "ipc_label": "SHOEING OF ANIMALS", + "match_score": 0.581 + }, + "A01P": { + "topic_id": "https://openalex.org/T14099", + "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", + "ipc_label": "BIOCIDAL, PEST REPELLANT, PEST ATTRACTANT OR PLANT GROWTH REGULATORY ACTIVITY OF CHEMICAL COMPOUNDS OR PREPARATIONS", + "match_score": 0.386 + }, + "A21C": { + "topic_id": "https://openalex.org/T12282", + "topic_display_name": "Mineral Processing and Grinding", + "ipc_label": "MACHINES OR EQUIPMENT FOR MAKING OR PROCESSING DOUGHSHANDLING BAKED ARTICLES MADE FROM DOUGH", + "match_score": 0.39 + }, + "A22B": { + "topic_id": "https://openalex.org/T13366", + "topic_display_name": "Accounting Theory and Financial Reporting", + "ipc_label": "SLAUGHTERING", + "match_score": 0.545 + }, + "A23K": { + "topic_id": "https://openalex.org/T12181", + "topic_display_name": "Agricultural and Biological Research", + "ipc_label": "FODDER", + "match_score": 0.444 + }, + "A23Y": { + "topic_id": "https://openalex.org/T12388", + "topic_display_name": "Identification and Quantification in Food", + "ipc_label": "INDEXING SCHEME RELATING TO LACTIC OR PROPIONIC ACID BACTERIA USED IN FOODSTUFFS OR FOOD PREPARATION", + "match_score": 0.369 + }, + "A24C": { + "topic_id": "https://openalex.org/T13832", + "topic_display_name": "Advanced Decision-Making Techniques", + "ipc_label": "MACHINES FOR MAKING CIGARS OR CIGARETTES", + "match_score": 0.475 + }, + "A41B": { + "topic_id": "https://openalex.org/T13368", + "topic_display_name": "University Challenges and Reforms", + "ipc_label": "SHIRTSUNDERWEARBABY LINENHANDKERCHIEFS", + "match_score": 0.451 + }, + "A41C": { + "topic_id": "https://openalex.org/T14190", + "topic_display_name": "Military history and social perspectives", + "ipc_label": "CORSETSBRASSIERES", + "match_score": 0.485 + }, + "A41D": { + "topic_id": "https://openalex.org/T13272", + "topic_display_name": "Psychological Treatments and Assessments", + "ipc_label": "OUTERWEARPROTECTIVE GARMENTSACCESSORIES", + "match_score": 0.43 + }, + "A41F": { + "topic_id": "https://openalex.org/T13129", + "topic_display_name": "Material Properties and Applications", + "ipc_label": "GARMENT FASTENINGSSUSPENDERS", + "match_score": 0.491 + }, + "A41G": { + "topic_id": "https://openalex.org/T13734", + "topic_display_name": "Advanced Computational Techniques and Applications", + "ipc_label": "ARTIFICIAL FLOWERSWIGSMASKSFEATHERS", + "match_score": 0.552 + }, + "A42C": { + "topic_id": "https://openalex.org/T11159", + "topic_display_name": "Manufacturing Process and Optimization", + "ipc_label": "MANUFACTURING OR TRIMMING HEAD COVERINGS, e.g. HATS", + "match_score": 0.494 + }, + "A43B": { + "topic_id": "https://openalex.org/T13232", + "topic_display_name": "Laser-Ablation Synthesis of Nanoparticles", + "ipc_label": "CHARACTERISTIC FEATURES OF FOOTWEARPARTS OF FOOTWEAR", + "match_score": 0.387 + }, + "A43C": { + "topic_id": "https://openalex.org/T13288", + "topic_display_name": "Banking, Crisis Management, COVID-19 Impact", + "ipc_label": "FASTENINGS OR ATTACHMENTS OF FOOTWEARLACES IN GENERAL", + "match_score": 0.375 + }, + "A43D": { + "topic_id": "https://openalex.org/T13290", + "topic_display_name": "Diverse Industrial Engineering Technologies", + "ipc_label": "MACHINES, TOOLS, EQUIPMENT OR METHODS FOR MANUFACTURING OR REPAIRING FOOTWEAR", + "match_score": 0.462 + }, + "A44C": { + "topic_id": "https://openalex.org/T12607", + "topic_display_name": "Personal Information Management and User Behavior", + "ipc_label": "PERSONAL ADORNMENTS, e.g. JEWELLERYCOINS", + "match_score": 0.449 + }, + "A44D": { + "topic_id": "https://openalex.org/T11334", + "topic_display_name": "Psychosomatic Disorders and Their Treatments", + "ipc_label": "INDEXING SCHEME RELATING TO BUTTONS, PINS, BUCKLES OR SLIDE FASTENERS, AND TO JEWELLERY, BRACELETS OR OTHER PERSONAL ADORNMENTS", + "match_score": 0.374 + }, + "A45C": { + "topic_id": "https://openalex.org/T10413", + "topic_display_name": "High-pressure geophysics and materials", + "ipc_label": "PURSESLUGGAGEHAND CARRIED BAGS", + "match_score": 0.471 + }, + "A45F": { + "topic_id": "https://openalex.org/T11867", + "topic_display_name": "Traumatic Ocular and Foreign Body Injuries", + "ipc_label": "TRAVELLING OR CAMP EQUIPMENT: SACKS OR PACKS CARRIED ON THE BODY", + "match_score": 0.358 + }, + "A46B": { + "topic_id": "https://openalex.org/T13398", + "topic_display_name": "Data Analysis with R", + "ipc_label": "BRUSHES handles not integral with brushware B25G", + "match_score": 0.353 + }, + "A46D": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "MANUFACTURE OF BRUSHES", + "match_score": 0.455 + }, + "A47B": { + "topic_id": "https://openalex.org/T14133", + "topic_display_name": "Border Security and International Relations", + "ipc_label": "TABLESDESKSOFFICE FURNITURECABINETSDRAWERSGENERAL DETAILS OF FURNITURE furniture jointing F16B", + "match_score": 0.35 + }, + "A47C": { + "topic_id": "https://openalex.org/T10495", + "topic_display_name": "Catalysts for Methane Reforming", + "ipc_label": "CHAIRS seats specially adapted for vehicles B60N2/00SOFASBEDS upholstery in general B68G", + "match_score": 0.353 + }, + "A47G": { + "topic_id": "https://openalex.org/T14160", + "topic_display_name": "Water management and technologies", + "ipc_label": "HOUSEHOLD OR TABLE EQUIPMENT book-ends A47B5/00; knives B26B", + "match_score": 0.366 + }, + "A47J": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "KITCHEN EQUIPMENTCOFFEE MILLSSPICE MILLSAPPARATUS FOR MAKING BEVERAGES", + "match_score": 0.378 + }, + "A61D": { + "topic_id": "https://openalex.org/T14236", + "topic_display_name": "Educational Tools and Methods", + "ipc_label": "VETERINARY INSTRUMENTS, IMPLEMENTS, TOOLS, OR METHODS", + "match_score": 0.512 + }, + "A61P": { + "topic_id": "https://openalex.org/T12685", + "topic_display_name": "Phytochemical compounds biological activities", + "ipc_label": "SPECIFIC THERAPEUTIC ACTIVITY OF CHEMICAL COMPOUNDS OR MEDICINAL PREPARATIONS", + "match_score": 0.525 + }, + "A61Q": { + "topic_id": "https://openalex.org/T10576", + "topic_display_name": "Opioid Use Disorder Treatment", + "ipc_label": "SPECIFIC USE OF COSMETICS OR SIMILAR TOILETRY PREPARATIONS", + "match_score": 0.437 + }, + "A62D": { + "topic_id": "https://openalex.org/T11802", + "topic_display_name": "Chemical Looping and Thermochemical Processes", + "ipc_label": "CHEMICAL MEANS FOR EXTINGUISHING FIRES OR FOR COMBATING OR PROTECTING AGAINST HARMFUL CHEMICAL AGENTSCHEMICAL MATERIALS FOR USE IN BREATHING APPARATUS", + "match_score": 0.369 + }, + "A63H": { + "topic_id": "https://openalex.org/T12105", + "topic_display_name": "Hygrothermal properties of building materials", + "ipc_label": "TOYS, e.g. TOPS, DOLLS, HOOPS OR BUILDING BLOCKS", + "match_score": 0.409 + }, + "A99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "B01B": { + "topic_id": "https://openalex.org/T11900", + "topic_display_name": "Fungal Plant Pathogen Control", + "ipc_label": "BOILINGBOILING APPARATUS ; EVAPORATION; EVAPORATION APPARATUS", + "match_score": 0.381 + }, + "B01J": { + "topic_id": "https://openalex.org/T13104", + "topic_display_name": "Chemical and Physical Properties of Materials", + "ipc_label": "CHEMICAL OR PHYSICAL PROCESSES, e.g. CATALYSIS OR COLLOID CHEMISTRYTHEIR RELEVANT APPARATUS", + "match_score": 0.471 + }, + "B01L": { + "topic_id": "https://openalex.org/T13104", + "topic_display_name": "Chemical and Physical Properties of Materials", + "ipc_label": "CHEMICAL OR PHYSICAL LABORATORY APPARATUS FOR GENERAL USE", + "match_score": 0.549 + }, + "B03B": { + "topic_id": "https://openalex.org/T11808", + "topic_display_name": "Superconducting Materials and Applications", + "ipc_label": "SEPARATING SOLID MATERIALS USING LIQUIDS OR USING PNEUMATIC TABLES OR JIGS", + "match_score": 0.448 + }, + "B09B": { + "topic_id": "https://openalex.org/T11108", + "topic_display_name": "Municipal Solid Waste Management", + "ipc_label": "DISPOSAL OF SOLID WASTE", + "match_score": 0.667 + }, + "B21G": { + "topic_id": "https://openalex.org/T10377", + "topic_display_name": "Metal and Thin Film Mechanics", + "ipc_label": "MAKING NEEDLES, PINS OR NAILS OF METAL", + "match_score": 0.4 + }, + "B22C": { + "topic_id": "https://openalex.org/T11853", + "topic_display_name": "Semiconductor materials and interfaces", + "ipc_label": "FOUNDRY MOULDING moulding refractory materials in general B28B", + "match_score": 0.48 + }, + "B23B": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "TURNINGBORING arrangements for copying or controlling B23Q", + "match_score": 0.424 + }, + "B24C": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "ABRASIVE OR RELATED BLASTING WITH PARTICULATE MATERIAL", + "match_score": 0.469 + }, + "B25H": { + "topic_id": "https://openalex.org/T10488", + "topic_display_name": "Nanocomposite Films for Food Packaging", + "ipc_label": "WORKSHOP EQUIPMENT, e.g. FOR MARKING-OUT WORKSTORAGE MEANS FOR WORKSHOPS storing or packaging B65", + "match_score": 0.356 + }, + "B27H": { + "topic_id": "https://openalex.org/T14076", + "topic_display_name": "Material Properties and Failure Mechanisms", + "ipc_label": "BENDING WOOD OR SIMILAR MATERIALCOOPERAGEMAKING WHEELS FROM WOOD OR SIMILAR MATERIAL", + "match_score": 0.381 + }, + "B27J": { + "topic_id": "https://openalex.org/T10219", + "topic_display_name": "Mechanical Behavior of Composites", + "ipc_label": "MECHANICAL WORKING OF CANE, CORK, OR SIMILAR MATERIALS", + "match_score": 0.575 + }, + "B28D": { + "topic_id": "https://openalex.org/T10811", + "topic_display_name": "Hydrogen Storage and Materials", + "ipc_label": "WORKING STONE OR STONE-LIKE MATERIALS", + "match_score": 0.567 + }, + "B29L": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS B29C, RELATING TO PARTICULAR ARTICLES", + "match_score": 0.393 + }, + "B41F": { + "topic_id": "https://openalex.org/T11523", + "topic_display_name": "Nanomaterials and Printing Technologies", + "ipc_label": "PRINTING MACHINES OR PRESSES manifolding devices or office printing machines B41L", + "match_score": 0.383 + }, + "B41P": { + "topic_id": "https://openalex.org/T13557", + "topic_display_name": "Environmental and sustainability education", + "ipc_label": "INDEXING SCHEME RELATING TO PRINTING, LINING MACHINES, TYPEWRITERS, AND TO STAMPS", + "match_score": 0.42 + }, + "B42P": { + "topic_id": "https://openalex.org/T11877", + "topic_display_name": "Iron oxide chemistry and applications", + "ipc_label": "INDEXING SCHEME RELATING TO BOOKS, FILING APPLIANCES OR THE LIKE", + "match_score": 0.416 + }, + "B44F": { + "topic_id": "https://openalex.org/T12174", + "topic_display_name": "Hospital Admissions and Outcomes", + "ipc_label": "SPECIAL DESIGNS OR PICTURES", + "match_score": 0.542 + }, + "B60C": { + "topic_id": "https://openalex.org/T12641", + "topic_display_name": "Historical and socio-economic studies of Spain and related regions", + "ipc_label": "VEHICLE TYRESTYRE INFLATIONTYRE CHANGINGCONNECTING VALVES TO INFLATABLE ELASTIC BODIES IN GENERALDEVICES OR ARRANGEMENTS RELATED TO TYRES", + "match_score": 0.384 + }, + "B60D": { + "topic_id": "https://openalex.org/T10829", + "topic_display_name": "Interconnection Networks and Systems", + "ipc_label": "VEHICLE CONNECTIONS components of brake systems B60T17/04", + "match_score": 0.473 + }, + "B60F": { + "topic_id": "https://openalex.org/T14022", + "topic_display_name": "Cultural and Religious Practices in Indonesia", + "ipc_label": "VEHICLES FOR USE BOTH ON RAIL AND ON ROADAMPHIBIOUS OR LIKE VEHICLESCONVERTIBLE VEHICLES air-cushion vehicles B60V", + "match_score": 0.377 + }, + "B60G": { + "topic_id": "https://openalex.org/T10805", + "topic_display_name": "Vehicle Dynamics and Control Systems", + "ipc_label": "VEHICLE SUSPENSION ARRANGEMENTS air-cushion vehicles B60V; cycle suspensions B62K25/00", + "match_score": 0.361 + }, + "B60H": { + "topic_id": "https://openalex.org/T10558", + "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", + "ipc_label": "ARRANGEMENTS OF HEATING, COOLING, VENTILATING OR OTHER AIR-TREATING DEVICES SPECIALLY ADAPTED FOR PASSENGER OR GOODS SPACES OF VEHICLES", + "match_score": 0.366 + }, + "B60Q": { + "topic_id": "https://openalex.org/T10558", + "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", + "ipc_label": "ARRANGEMENT OF SIGNALLING OR LIGHTING DEVICES, THE MOUNTING OR SUPPORTING THEREOF OR CIRCUITS THEREFOR, FOR VEHICLES IN GENERAL", + "match_score": 0.415 + }, + "B60R": { + "topic_id": "https://openalex.org/T12707", + "topic_display_name": "Vehicle License Plate Recognition", + "ipc_label": "VEHICLES, VEHICLE FITTINGS, OR VEHICLE PARTS, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.381 + }, + "B60V": { + "topic_id": "https://openalex.org/T11002", + "topic_display_name": "Indoor Air Quality and Microbial Exposure", + "ipc_label": "AIR-CUSHION VEHICLES", + "match_score": 0.393 + }, + "B60Y": { + "topic_id": "https://openalex.org/T12898", + "topic_display_name": "Induction Heating and Inverter Technology", + "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS CROSS-CUTTING VEHICLE TECHNOLOGY", + "match_score": 0.569 + }, + "B61D": { + "topic_id": "https://openalex.org/T12271", + "topic_display_name": "Renewable energy and sustainable power systems", + "ipc_label": "BODY DETAILS OR KINDS OF RAILWAY VEHICLES vehicles in general B60; adaptation of vehicles to special systems B61B; underframes B61F", + "match_score": 0.35 + }, + "B61G": { + "topic_id": "https://openalex.org/T14049", + "topic_display_name": "Plant and Fungal Species Descriptions", + "ipc_label": "COUPLINGSDRAUGHT AND BUFFING APPLIANCES vehicle connections in general B60D", + "match_score": 0.446 + }, + "B61J": { + "topic_id": "https://openalex.org/T10757", + "topic_display_name": "Geographic Information Systems Studies", + "ipc_label": "SHIFTING OR SHUNTING OF RAIL VEHICLES shifting vehicles in general B60S; marshalling systems B61B", + "match_score": 0.37 + }, + "B62C": { + "topic_id": "https://openalex.org/T13551", + "topic_display_name": "Biochemical effects in animals", + "ipc_label": "VEHICLES DRAWN BY ANIMALS", + "match_score": 0.582 + }, + "B63J": { + "topic_id": "https://openalex.org/T11427", + "topic_display_name": "Elbow and Forearm Trauma Treatment", + "ipc_label": "AUXILIARIES ON VESSELS", + "match_score": 0.444 + }, + "B64B": { + "topic_id": "https://openalex.org/T12916", + "topic_display_name": "COVID-19 impact on air quality", + "ipc_label": "LIGHTER-THAN AIR AIRCRAFT", + "match_score": 0.4 + }, + "B64C": { + "topic_id": "https://openalex.org/T10647", + "topic_display_name": "Coastal and Marine Dynamics", + "ipc_label": "AEROPLANESHELICOPTERS", + "match_score": 0.49 + }, + "B64U": { + "topic_id": "https://openalex.org/T11192", + "topic_display_name": "Underwater Vehicles and Communication Systems", + "ipc_label": "UNMANNED AERIAL VEHICLES [UAV]EQUIPMENT THEREFOR", + "match_score": 0.43 + }, + "B65H": { + "topic_id": "https://openalex.org/T13917", + "topic_display_name": "Engineering and Material Science Research", + "ipc_label": "HANDLING THIN OR FILAMENTARY MATERIAL, e.g. SHEETS, WEBS, CABLES", + "match_score": 0.419 + }, + "B68B": { + "topic_id": "https://openalex.org/T12617", + "topic_display_name": "Energy, Environment, and Transportation Policies", + "ipc_label": "HARNESSDEVICES USED IN CONNECTION THEREWITHWHIPS OR THE LIKE", + "match_score": 0.389 + }, + "B68C": { + "topic_id": "https://openalex.org/T13896", + "topic_display_name": "Health Services Management and Policy", + "ipc_label": "SADDLESSTIRRUPS", + "match_score": 0.424 + }, + "B81B": { + "topic_id": "https://openalex.org/T12111", + "topic_display_name": "Industrial Vision Systems and Defect Detection", + "ipc_label": "MICROSTRUCTURAL DEVICES OR SYSTEMS, e.g. MICROMECHANICAL DEVICES piezo-electric, electrostrictive or magnetostrictive elements per se H10N30/00", + "match_score": 0.37 + }, + "B82Y": { + "topic_id": "https://openalex.org/T11169", + "topic_display_name": "Silicon Nanostructures and Photoluminescence", + "ipc_label": "SPECIFIC USES OR APPLICATIONS OF NANOSTRUCTURESMEASUREMENT OR ANALYSIS OF NANOSTRUCTURESMANUFACTURE OR TREATMENT OF NANOSTRUCTURES", + "match_score": 0.402 + }, + "B99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "C01B": { + "topic_id": "https://openalex.org/T12458", + "topic_display_name": "Organometallic Compounds Synthesis and Characterization", + "ipc_label": "NON-METALLIC ELEMENTSCOMPOUNDS THEREOF; METALLOIDS OR COMPOUNDS THEREOF NOT COVERED BY SUBCLASS C01C", + "match_score": 0.4 + }, + "C01P": { + "topic_id": "https://openalex.org/T12410", + "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", + "ipc_label": "INDEXING SCHEME RELATING TO STRUCTURAL AND PHYSICAL ASPECTS OF SOLID INORGANIC COMPOUNDS", + "match_score": 0.658 + }, + "C03B": { + "topic_id": "https://openalex.org/T10705", + "topic_display_name": "Additive Manufacturing Materials and Processes", + "ipc_label": "MANUFACTURE, SHAPING, OR SUPPLEMENTARY PROCESSES", + "match_score": 0.574 + }, + "C05B": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "PHOSPHATIC FERTILISERS", + "match_score": 0.5 + }, + "C05C": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "NITROGENOUS FERTILISERS", + "match_score": 0.444 + }, + "C05D": { + "topic_id": "https://openalex.org/T10973", + "topic_display_name": "Radioactive element chemistry and processing", + "ipc_label": "INORGANIC FERTILISERS NOT COVERED BY SUBCLASSES C05B, C05CFERTILISERS PRODUCING CARBON DIOXIDE", + "match_score": 0.362 + }, + "C06F": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "MATCHESMANUFACTURE OF MATCHES", + "match_score": 0.588 + }, + "C07B": { + "topic_id": "https://openalex.org/T14099", + "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", + "ipc_label": "GENERAL METHODS OF ORGANIC CHEMISTRYAPPARATUS THEREFOR preparation of carboxylic acid esters by telomerisation C07C67/47; telomerisation C08F", + "match_score": 0.355 + }, + "C07C": { + "topic_id": "https://openalex.org/T13208", + "topic_display_name": "Synthesis of heterocyclic compounds", + "ipc_label": "ACYCLIC OR CARBOCYCLIC COMPOUNDS", + "match_score": 0.657 + }, + "C07D": { + "topic_id": "https://openalex.org/T13208", + "topic_display_name": "Synthesis of heterocyclic compounds", + "ipc_label": "HETEROCYCLIC COMPOUNDS macromolecular compounds C08", + "match_score": 0.512 + }, + "C07G": { + "topic_id": "https://openalex.org/T12055", + "topic_display_name": "Boron Compounds in Chemistry", + "ipc_label": "COMPOUNDS OF UNKNOWN CONSTITUTION", + "match_score": 0.492 + }, + "C07J": { + "topic_id": "https://openalex.org/T10310", + "topic_display_name": "Corrosion Behavior and Inhibition", + "ipc_label": "STEROIDS seco-steroids C07C", + "match_score": 0.455 + }, + "C08C": { + "topic_id": "https://openalex.org/T13037", + "topic_display_name": "Piperaceae Chemical and Biological Studies", + "ipc_label": "TREATMENT OR CHEMICAL MODIFICATION OF RUBBERS", + "match_score": 0.506 + }, + "C08F": { + "topic_id": "https://openalex.org/T13239", + "topic_display_name": "Phosphorus compounds and reactions", + "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED BY REACTIONS ONLY INVOLVING CARBON-TO-CARBON UNSATURATED BONDS", + "match_score": 0.4 + }, + "C08G": { + "topic_id": "https://openalex.org/T14459", + "topic_display_name": "Synthesis and Reactions of Organic Compounds", + "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED OTHERWISE THAN BY REACTIONS ONLY INVOLVING UNSATURATED CARBON-TO-CARBON BONDS", + "match_score": 0.387 + }, + "C09F": { + "topic_id": "https://openalex.org/T11823", + "topic_display_name": "Natural Resources and Economic Development", + "ipc_label": "NATURAL RESINSFRENCH POLISHDRYING-OILSDRIERS (SICCATIVES)TURPENTINE", + "match_score": 0.422 + }, + "C09G": { + "topic_id": "https://openalex.org/T12638", + "topic_display_name": "Pomegranate: compositions and health benefits", + "ipc_label": "POLISHING COMPOSITIONS French polish C09F11/00SKI WAXES", + "match_score": 0.42 + }, + "C09H": { + "topic_id": "https://openalex.org/T14032", + "topic_display_name": "History and International Relations", + "ipc_label": "PREPARATION OF GLUE OR GELATINE", + "match_score": 0.485 + }, + "C09K": { + "topic_id": "https://openalex.org/T10245", + "topic_display_name": "Metamaterials and Metasurfaces Applications", + "ipc_label": "MATERIALS FOR MISCELLANEOUS APPLICATIONS, NOT PROVIDED FOR ELSEWHERE", + "match_score": 0.523 + }, + "C10F": { + "topic_id": "https://openalex.org/T10650", + "topic_display_name": "Food Drying and Modeling", + "ipc_label": "DRYING OR WORKING-UP OF PEAT", + "match_score": 0.423 + }, + "C10H": { + "topic_id": "https://openalex.org/T12931", + "topic_display_name": "Educational Methods and Outcomes", + "ipc_label": "PRODUCTION OF ACETYLENE BY WET METHODS purification of acetylene C07C7/00", + "match_score": 0.457 + }, + "C10K": { + "topic_id": "https://openalex.org/T11848", + "topic_display_name": "Heme Oxygenase-1 and Carbon Monoxide", + "ipc_label": "PURIFYING OR MODIFYING THE CHEMICAL COMPOSITION OF COMBUSTIBLE GASES CONTAINING CARBON MONOXIDE", + "match_score": 0.412 + }, + "C10N": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS C10M RELATING TO LUBRICATING COMPOSITIONS", + "match_score": 0.397 + }, + "C11D": { + "topic_id": "https://openalex.org/T11869", + "topic_display_name": "Per- and polyfluoroalkyl substances research", + "ipc_label": "DETERGENT COMPOSITIONSUSE OF SINGLE SUBSTANCES AS DETERGENTSSOAP OR SOAP-MAKINGRESIN SOAPSRECOVERY OF GLYCEROL", + "match_score": 0.351 + }, + "C12J": { + "topic_id": "https://openalex.org/T12008", + "topic_display_name": "Solar-Powered Water Purification Methods", + "ipc_label": "VINEGARPREPARATION OR PURIFICATION THEREOF", + "match_score": 0.61 + }, + "C12R": { + "topic_id": "https://openalex.org/T10685", + "topic_display_name": "Viral-associated cancers and disorders", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES C12C - C12Q, RELATING TO MICROORGANISMS", + "match_score": 0.367 + }, + "C12Y": { + "topic_id": "https://openalex.org/T12770", + "topic_display_name": "Amino Acid Enzymes and Metabolism", + "ipc_label": "ENZYMES", + "match_score": 1.0 + }, + "C13B": { + "topic_id": "https://openalex.org/T12410", + "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", + "ipc_label": "PRODUCTION OF SUCROSEAPPARATUS SPECIALLY ADAPTED THEREFOR chemically synthesised sugars or sugar derivatives C07H; fermentation or enzyme-using processes for preparing compounds containing saccharide radicals C12P19/00", + "match_score": 0.351 + }, + "C21B": { + "topic_id": "https://openalex.org/T12301", + "topic_display_name": "Facial Nerve Paralysis Treatment and Research", + "ipc_label": "MANUFACTURE OF IRON OR STEEL preliminary treatment of ferrous ores or scrap C22B1/00; electric heating H05B", + "match_score": 0.368 + }, + "C22B": { + "topic_id": "https://openalex.org/T13652", + "topic_display_name": "Education and Social Development in Ukraine", + "ipc_label": "PRODUCTION AND REFINING OF METALS electrolytic C25PRETREATMENT OF RAW MATERIALS", + "match_score": 0.475 + }, + "C22C": { + "topic_id": "https://openalex.org/T11453", + "topic_display_name": "Diagnosis and Treatment of Venous Diseases", + "ipc_label": "ALLOYS flints C06C15/00; treatment of alloys C21D, C22F", + "match_score": 0.474 + }, + "C23D": { + "topic_id": "https://openalex.org/T13463", + "topic_display_name": "Nanoporous metals and alloys", + "ipc_label": "ENAMELLING OF, OR APPLYING A VITREOUS LAYER TO, METALS", + "match_score": 0.39 + }, + "C23G": { + "topic_id": "https://openalex.org/T14068", + "topic_display_name": "Organic and Inorganic Chemical Reactions", + "ipc_label": "CLEANING OR DE-GREASING OF METALLIC MATERIAL BY CHEMICAL METHODS OTHER THAN ELECTROLYSIS", + "match_score": 0.438 + }, + "C25C": { + "topic_id": "https://openalex.org/T10962", + "topic_display_name": "Thermodynamic properties of mixtures", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC PRODUCTION, RECOVERY OR REFINING OF METALSAPPARATUS THEREFOR", + "match_score": 0.378 + }, + "C25D": { + "topic_id": "https://openalex.org/T14382", + "topic_display_name": "Electrophoretic Deposition in Materials Science", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC OR ELECTROPHORETIC PRODUCTION OF COATINGSELECTROFORMINGAPPARATUS THEREFOR", + "match_score": 0.424 + }, + "C25F": { + "topic_id": "https://openalex.org/T11025", + "topic_display_name": "Nonlinear Optical Materials Research", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC REMOVAL OF MATERIALS FROM OBJECTSAPPARATUS THEREFOR", + "match_score": 0.458 + }, + "C99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "D01D": { + "topic_id": "https://openalex.org/T11416", + "topic_display_name": "Numerical methods for differential equations", + "ipc_label": "MECHANICAL METHODS OR APPARATUS IN THE MANUFACTURE OF ARTIFICIAL FILAMENTS, THREADS, FIBRES, BRISTLES OR RIBBONS", + "match_score": 0.397 + }, + "D02G": { + "topic_id": "https://openalex.org/T14192", + "topic_display_name": "Literature, Film, and Journalism Analysis", + "ipc_label": "CRIMPING OR CURLING FIBRES, FILAMENTS, THREADS, OR YARNSYARNS OR THREADS", + "match_score": 0.389 + }, + "D02H": { + "topic_id": "https://openalex.org/T13523", + "topic_display_name": "Mathematics, Computing, and Information Processing", + "ipc_label": "WARPING, BEAMING OR LEASING", + "match_score": 0.468 + }, + "D03C": { + "topic_id": "https://openalex.org/T12490", + "topic_display_name": "Software Engineering and Design Patterns", + "ipc_label": "SHEDDING MECHANISMSPATTERN CARDS OR CHAINSPUNCHING OF CARDSDESIGNING PATTERNS", + "match_score": 0.41 + }, + "D03D": { + "topic_id": "https://openalex.org/T13880", + "topic_display_name": "Innovative Education Methods and Tools", + "ipc_label": "WOVEN FABRICSMETHODS OF WEAVINGLOOMS", + "match_score": 0.459 + }, + "D03J": { + "topic_id": "https://openalex.org/T10262", + "topic_display_name": "Microwave Engineering and Waveguides", + "ipc_label": "AUXILIARY WEAVING APPARATUSWEAVERS' TOOLSSHUTTLES", + "match_score": 0.4 + }, + "D04B": { + "topic_id": "https://openalex.org/T13366", + "topic_display_name": "Accounting Theory and Financial Reporting", + "ipc_label": "KNITTING", + "match_score": 0.556 + }, + "D05C": { + "topic_id": "https://openalex.org/T13583", + "topic_display_name": "Jury Decision Making Processes", + "ipc_label": "EMBROIDERINGTUFTING making non-woven fabrics D04H; sewing D05B", + "match_score": 0.391 + }, + "D05D": { + "topic_id": "https://openalex.org/T14497", + "topic_display_name": "Social Issues and Policies in Latin America", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES D05B AND D05C, RELATING TO SEWING, EMBROIDERING AND TUFTING", + "match_score": 0.4 + }, + "D06C": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "FINISHING, DRESSING, TENTERING OR STRETCHING TEXTILE FABRICS", + "match_score": 0.484 + }, + "D06F": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "LAUNDERING, DRYING, IRONING, PRESSING OR FOLDING TEXTILE ARTICLES", + "match_score": 0.44 + }, + "D06H": { + "topic_id": "https://openalex.org/T11948", + "topic_display_name": "Machine Learning in Materials Science", + "ipc_label": "MARKING, INSPECTING, SEAMING OR SEVERING TEXTILE MATERIALS seaming by sewing D05B", + "match_score": 0.475 + }, + "D06P": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "DYEING OR PRINTING TEXTILESDYEING LEATHER, FURS OR SOLID MACROMOLECULAR SUBSTANCES IN ANY FORM", + "match_score": 0.372 + }, + "D10B": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBLASSES OF SECTION D, RELATING TO TEXTILES", + "match_score": 0.4 + }, + "D21B": { + "topic_id": "https://openalex.org/T11485", + "topic_display_name": "Gastrointestinal Tumor Research and Treatment", + "ipc_label": "FIBROUS RAW MATERIALS OR THEIR MECHANICAL TREATMENT", + "match_score": 0.562 + }, + "D21D": { + "topic_id": "https://openalex.org/T11071", + "topic_display_name": "Treatment of Major Depression", + "ipc_label": "TREATMENT OF THE MATERIALS BEFORE PASSING TO THE PAPER-MAKING MACHINE", + "match_score": 0.469 + }, + "D99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "E01F": { + "topic_id": "https://openalex.org/T14390", + "topic_display_name": "Real estate and construction management", + "ipc_label": "ADDITIONAL WORK, SUCH AS EQUIPPING ROADS OR THE CONSTRUCTION OF PLATFORMS, HELICOPTER LANDING STAGES, SIGNS, SNOW FENCES, OR THE LIKE", + "match_score": 0.36 + }, + "E02B": { + "topic_id": "https://openalex.org/T12907", + "topic_display_name": "Mechanical Engineering and Vibrations Research", + "ipc_label": "HYDRAULIC ENGINEERING ship-lifting E02C; dredging E02F", + "match_score": 0.5 + }, + "E02C": { + "topic_id": "https://openalex.org/T13253", + "topic_display_name": "Chemical Reactions and Mechanisms", + "ipc_label": "SHIP-LIFTING DEVICES OR MECHANISMS", + "match_score": 0.567 + }, + "E02D": { + "topic_id": "https://openalex.org/T12233", + "topic_display_name": "Geotechnical Engineering and Underground Structures", + "ipc_label": "FOUNDATIONSEXCAVATIONSEMBANKMENTS specially adapted for hydraulic engineering E02BUNDERGROUND OR UNDERWATER STRUCTURES tunnels, tunnelling, mining E21", + "match_score": 0.408 + }, + "E02F": { + "topic_id": "https://openalex.org/T13027", + "topic_display_name": "Applied Advanced Technologies", + "ipc_label": "DREDGINGSOIL-SHIFTING winning peat E21C49/00", + "match_score": 0.381 + }, + "E03D": { + "topic_id": "https://openalex.org/T14249", + "topic_display_name": "Water Quality Monitoring and Analysis", + "ipc_label": "WATER-CLOSETS OR URINALS WITH FLUSHING DEVICESFLUSHING VALVES THEREFOR", + "match_score": 0.355 + }, + "E03F": { + "topic_id": "https://openalex.org/T13675", + "topic_display_name": "Diffusion Coefficients in Liquids", + "ipc_label": "SEWERSCESSPOOLS", + "match_score": 0.444 + }, + "E05B": { + "topic_id": "https://openalex.org/T10859", + "topic_display_name": "Polymer Surface Interaction Studies", + "ipc_label": "LOCKSACCESSORIES THEREFORHANDCUFFS", + "match_score": 0.452 + }, + "E21C": { + "topic_id": "https://openalex.org/T11933", + "topic_display_name": "Mining and Resource Management", + "ipc_label": "MINING OR QUARRYING", + "match_score": 0.531 + }, + "E21F": { + "topic_id": "https://openalex.org/T10570", + "topic_display_name": "Drug Transport and Resistance Mechanisms", + "ipc_label": "SAFETY DEVICES, TRANSPORT, FILLING-UP, RESCUE, VENTILATION, OR DRAINING IN OR OF MINES OR TUNNELS", + "match_score": 0.38 + }, + "E99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "F01L": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "CYCLICALLY OPERATING VALVES FOR MACHINES OR ENGINES", + "match_score": 0.478 + }, + "F02F": { + "topic_id": "https://openalex.org/T10117", + "topic_display_name": "Advanced Combustion Engine Technologies", + "ipc_label": "CYLINDERS, PISTONS OR CASINGS, FOR COMBUSTION ENGINESARRANGEMENTS OF SEALINGS IN COMBUSTION ENGINES", + "match_score": 0.406 + }, + "F02M": { + "topic_id": "https://openalex.org/T13917", + "topic_display_name": "Engineering and Material Science Research", + "ipc_label": "SUPPLYING COMBUSTION ENGINES IN GENERAL WITH COMBUSTIBLE MIXTURES OR CONSTITUENTS THEREOF", + "match_score": 0.385 + }, + "F02N": { + "topic_id": "https://openalex.org/T10117", + "topic_display_name": "Advanced Combustion Engine Technologies", + "ipc_label": "STARTING OF COMBUSTION ENGINESSTARTING AIDS FOR SUCH ENGINES, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.441 + }, + "F03D": { + "topic_id": "https://openalex.org/T10504", + "topic_display_name": "Sensorless Control of Electric Motors", + "ipc_label": "WIND MOTORS", + "match_score": 0.5 + }, + "F03H": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "PRODUCING A REACTIVE PROPULSIVE THRUST, NOT OTHERWISE PROVIDED FOR from combustion products F02K", + "match_score": 0.35 + }, + "F16C": { + "topic_id": "https://openalex.org/T14144", + "topic_display_name": "Neurological Disease Mechanisms and Treatments", + "ipc_label": "SHAFTSFLEXIBLE SHAFTSELEMENTS OR CRANKSHAFT MECHANISMSROTARY BODIES OTHER THAN GEARING ELEMENTSBEARINGS", + "match_score": 0.376 + }, + "F16D": { + "topic_id": "https://openalex.org/T12240", + "topic_display_name": "Nanomaterials for catalytic reactions", + "ipc_label": "COUPLINGS FOR TRANSMITTING ROTATIONCLUTCHESBRAKES", + "match_score": 0.465 + }, + "F16F": { + "topic_id": "https://openalex.org/T10030", + "topic_display_name": "Electrocatalysts for Energy Conversion", + "ipc_label": "SPRINGSSHOCK-ABSORBERSMEANS FOR DAMPING VIBRATION", + "match_score": 0.437 + }, + "F16H": { + "topic_id": "https://openalex.org/T14252", + "topic_display_name": "Water and Wastewater Treatment", + "ipc_label": "GEARING", + "match_score": 0.667 + }, + "F16J": { + "topic_id": "https://openalex.org/T14353", + "topic_display_name": "Wireless Sensor Networks for Data Analysis", + "ipc_label": "PISTONS specially adapted for dampers F16F9/32CYLINDERSSEALINGS", + "match_score": 0.4 + }, + "F16L": { + "topic_id": "https://openalex.org/T11343", + "topic_display_name": "Power Transformer Diagnostics and Insulation", + "ipc_label": "PIPESJOINTS OR FITTINGS FOR PIPESSUPPORTS FOR PIPES, CABLES OR PROTECTIVE TUBINGMEANS FOR THERMAL INSULATION IN GENERAL", + "match_score": 0.356 + }, + "F16N": { + "topic_id": "https://openalex.org/T14075", + "topic_display_name": "Psychodrama and Leishmaniasis Studies", + "ipc_label": "LUBRICATING", + "match_score": 0.6 + }, + "F16P": { + "topic_id": "https://openalex.org/T11317", + "topic_display_name": "Fire dynamics and safety research", + "ipc_label": "SAFETY DEVICES IN GENERAL; SAFETY DEVICES FOR PRESSES", + "match_score": 0.488 + }, + "F16S": { + "topic_id": "https://openalex.org/T10915", + "topic_display_name": "Trace Elements in Health", + "ipc_label": "CONSTRUCTIONAL ELEMENTS IN GENERALSTRUCTURES BUILT-UP FROM SUCH ELEMENTS, IN GENERAL", + "match_score": 0.389 + }, + "F21L": { + "topic_id": "https://openalex.org/T13000", + "topic_display_name": "World Systems and Global Transformations", + "ipc_label": "LIGHTING DEVICES OR SYSTEMS THEREOF, BEING PORTABLE OR SPECIALLY ADAPTED FOR TRANSPORTATION", + "match_score": 0.427 + }, + "F21W": { + "topic_id": "https://openalex.org/T13257", + "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES F21K, F21L, F21S and F21V, RELATING TO USES OR APPLICATIONS OF LIGHTING DEVICES OR SYSTEMS", + "match_score": 0.383 + }, + "F22G": { + "topic_id": "https://openalex.org/T13960", + "topic_display_name": "Dietetics, Nutrition, and Education", + "ipc_label": "SUPERHEATING OF STEAM steam separating arrangements in boilers F22B37/26", + "match_score": 0.416 + }, + "F23D": { + "topic_id": "https://openalex.org/T11069", + "topic_display_name": "Testicular diseases and treatments", + "ipc_label": "BURNERS", + "match_score": 0.571 + }, + "F23G": { + "topic_id": "https://openalex.org/T14505", + "topic_display_name": "Natural Products and Applications", + "ipc_label": "CREMATION FURNACESCONSUMING WASTE PRODUCTS BY COMBUSTION", + "match_score": 0.472 + }, + "F23K": { + "topic_id": "https://openalex.org/T10806", + "topic_display_name": "Energetic Materials and Combustion", + "ipc_label": "FEEDING FUEL TO COMBUSTION APPARATUS fuel feeders specially adapted for fluidised bed combustion apparatus F23C10/22", + "match_score": 0.373 + }, + "F24S": { + "topic_id": "https://openalex.org/T10108", + "topic_display_name": "Electoral Systems and Political Participation", + "ipc_label": "SOLAR HEAT COLLECTORSSOLAR HEAT SYSTEMS for producing mechanical power from solar energy F03G6/00", + "match_score": 0.423 + }, + "F24T": { + "topic_id": "https://openalex.org/T11225", + "topic_display_name": "Geothermal Energy Systems and Applications", + "ipc_label": "GEOTHERMAL COLLECTORSGEOTHERMAL SYSTEMS", + "match_score": 0.667 + }, + "F24V": { + "topic_id": "https://openalex.org/T10171", + "topic_display_name": "Biofuel production and bioconversion", + "ipc_label": "COLLECTION, PRODUCTION OR USE OF HEAT NOT OTHERWISE PROVIDED FOR", + "match_score": 0.42 + }, + "F25B": { + "topic_id": "https://openalex.org/T13985", + "topic_display_name": "Enterprise Management and Information Systems", + "ipc_label": "REFRIGERATION MACHINES, PLANTS OR SYSTEMSCOMBINED HEATING AND REFRIGERATION SYSTEMSHEAT PUMP SYSTEMS", + "match_score": 0.414 + }, + "F25C": { + "topic_id": "https://openalex.org/T12544", + "topic_display_name": "Working Capital and Financial Performance", + "ipc_label": "PRODUCING, WORKING OR HANDLING ICE", + "match_score": 0.453 + }, + "F27M": { + "topic_id": "https://openalex.org/T10055", + "topic_display_name": "Diverse Aspects of Tourism Research", + "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS OF THE CHARGES OR FURNACES, KILNS, OVENS OR RETORTS", + "match_score": 0.41 + }, + "F28F": { + "topic_id": "https://openalex.org/T11655", + "topic_display_name": "HIV-related health complications and treatments", + "ipc_label": "DETAILS OF HEAT-EXCHANGE AND HEAT-TRANSFER APPARATUS, OF GENERAL APPLICATION water and air traps, air venting F16", + "match_score": 0.412 + }, + "F41A": { + "topic_id": "https://openalex.org/T13468", + "topic_display_name": "Educational Research and Science Teaching", + "ipc_label": "FUNCTIONAL FEATURES OR DETAILS COMMON TO BOTH SMALLARMS AND ORDNANCE, e.g. CANNONSMOUNTINGS FOR SMALLARMS OR ORDNANCE", + "match_score": 0.367 + }, + "F41G": { + "topic_id": "https://openalex.org/T13049", + "topic_display_name": "Surface Roughness and Optical Measurements", + "ipc_label": "WEAPON SIGHTSAIMING optical aspects thereof G02B", + "match_score": 0.467 + }, + "F99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "G01F": { + "topic_id": "https://openalex.org/T10836", + "topic_display_name": "Metabolomics and Mass Spectrometry Studies", + "ipc_label": "MEASURING VOLUME, VOLUME FLOW, MASS FLOW OR LIQUID LEVELMETERING BY VOLUME", + "match_score": 0.379 + }, + "G01G": { + "topic_id": "https://openalex.org/T13960", + "topic_display_name": "Dietetics, Nutrition, and Education", + "ipc_label": "WEIGHING sorting by weighing B07C5/16", + "match_score": 0.364 + }, + "G01H": { + "topic_id": "https://openalex.org/T10386", + "topic_display_name": "Microstructure and Mechanical Properties of Steels", + "ipc_label": "MEASUREMENT OF MECHANICAL VIBRATIONS OR ULTRASONIC, SONIC OR INFRASONIC WAVES", + "match_score": 0.425 + }, + "G01L": { + "topic_id": "https://openalex.org/T10386", + "topic_display_name": "Microstructure and Mechanical Properties of Steels", + "ipc_label": "MEASURING FORCE, STRESS, TORQUE, WORK, MECHANICAL POWER, MECHANICAL EFFICIENCY, OR FLUID PRESSURE weighing G01G", + "match_score": 0.385 + }, + "G01Q": { + "topic_id": "https://openalex.org/T10801", + "topic_display_name": "Synthetic Aperture Radar (SAR) Applications and Techniques", + "ipc_label": "SCANNING-PROBE TECHNIQUES OR APPARATUSAPPLICATIONS OF SCANNING-PROBE TECHNIQUES, e.g. SCANNING PROBE MICROSCOPY [SPM]", + "match_score": 0.389 + }, + "G01R": { + "topic_id": "https://openalex.org/T10614", + "topic_display_name": "Transcranial Magnetic Stimulation Studies", + "ipc_label": "MEASURING ELECTRIC VARIABLESMEASURING MAGNETIC VARIABLES indicating correct tuning of resonant circuits H03J3/12", + "match_score": 0.379 + }, + "G02B": { + "topic_id": "https://openalex.org/T12391", + "topic_display_name": "Artificial Immune Systems Applications", + "ipc_label": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS", + "match_score": 0.579 + }, + "G04D": { + "topic_id": "https://openalex.org/T13583", + "topic_display_name": "Jury Decision Making Processes", + "ipc_label": "APPARATUS OR TOOLS SPECIALLY DESIGNED FOR MAKING OR MAINTAINING CLOCKS OR WATCHES", + "match_score": 0.378 + }, + "G04F": { + "topic_id": "https://openalex.org/T13293", + "topic_display_name": "Engineering and Test Systems", + "ipc_label": "TIME-INTERVAL MEASURING measuring pulse characteristics G01R, e.g. G01R29/02; in radar or like systems G01S", + "match_score": 0.37 + }, + "G04G": { + "topic_id": "https://openalex.org/T10350", + "topic_display_name": "Electronic Health Records Systems", + "ipc_label": "ELECTRONIC TIME-PIECES", + "match_score": 0.582 + }, + "G04R": { + "topic_id": "https://openalex.org/T12810", + "topic_display_name": "Real-time simulation and control systems", + "ipc_label": "RADIO-CONTROLLED TIME-PIECES", + "match_score": 0.441 + }, + "G05D": { + "topic_id": "https://openalex.org/T10504", + "topic_display_name": "Sensorless Control of Electric Motors", + "ipc_label": "SYSTEMS FOR CONTROLLING OR REGULATING NON-ELECTRIC VARIABLES", + "match_score": 0.536 + }, + "G06C": { + "topic_id": "https://openalex.org/T13155", + "topic_display_name": "Digital Communication and Language", + "ipc_label": "DIGITAL COMPUTERS IN WHICH ALL THE COMPUTATION IS EFFECTED MECHANICALLY score computers for card games A63F1/18", + "match_score": 0.372 + }, + "G06D": { + "topic_id": "https://openalex.org/T12923", + "topic_display_name": "Digital Image Processing Techniques", + "ipc_label": "DIGITAL FLUID-PRESSURE COMPUTING DEVICES", + "match_score": 0.587 + }, + "G06F": { + "topic_id": "https://openalex.org/T13093", + "topic_display_name": "Electric Power Systems and Control", + "ipc_label": "ELECTRIC DIGITAL DATA PROCESSING computer systems based on specific computational models G06N", + "match_score": 0.472 + }, + "G06G": { + "topic_id": "https://openalex.org/T11429", + "topic_display_name": "Semiconductor Lasers and Optical Devices", + "ipc_label": "ANALOGUE COMPUTERS analogue optical computing devices G06E3/00", + "match_score": 0.529 + }, + "G06K": { + "topic_id": "https://openalex.org/T10627", + "topic_display_name": "Advanced Image and Video Retrieval Techniques", + "ipc_label": "GRAPHICAL DATA READING image or video recognition or understanding G06VPRESENTATION OF DATARECORD CARRIERSHANDLING RECORD CARRIERS", + "match_score": 0.354 + }, + "G06N": { + "topic_id": "https://openalex.org/T13806", + "topic_display_name": "Mathematical and Computational Methods", + "ipc_label": "COMPUTING ARRANGEMENTS BASED ON SPECIFIC COMPUTATIONAL MODELS", + "match_score": 0.525 + }, + "G06T": { + "topic_id": "https://openalex.org/T14339", + "topic_display_name": "Image Processing and 3D Reconstruction", + "ipc_label": "IMAGE DATA PROCESSING OR GENERATION, IN GENERAL", + "match_score": 0.541 + }, + "G06V": { + "topic_id": "https://openalex.org/T13579", + "topic_display_name": "Image and Video Stabilization", + "ipc_label": "IMAGE OR VIDEO RECOGNITION OR UNDERSTANDING", + "match_score": 0.75 + }, + "G07G": { + "topic_id": "https://openalex.org/T13321", + "topic_display_name": "Radio, Podcasts, and Digital Media", + "ipc_label": "REGISTERING THE RECEIPT OF CASH, VALUABLES, OR TOKENS digital computing in general G06C, G06F", + "match_score": 0.378 + }, + "G08B": { + "topic_id": "https://openalex.org/T11902", + "topic_display_name": "Intelligent Tutoring Systems and Adaptive Learning", + "ipc_label": "SIGNALLING OR CALLING SYSTEMSORDER TELEGRAPHSALARM SYSTEMS", + "match_score": 0.5 + }, + "G09F": { + "topic_id": "https://openalex.org/T14032", + "topic_display_name": "History and International Relations", + "ipc_label": "DISPLAYINGADVERTISINGSIGNSLABELS OR NAME-PLATESSEALS", + "match_score": 0.391 + }, + "G10L": { + "topic_id": "https://openalex.org/T13244", + "topic_display_name": "Analysis of environmental and stochastic processes", + "ipc_label": "SPEECH ANALYSIS OR SYNTHESISSPEECH RECOGNITIONSPEECH OR VOICE PROCESSINGSPEECH OR AUDIO CODING OR DECODING", + "match_score": 0.359 + }, + "G11C": { + "topic_id": "https://openalex.org/T10472", + "topic_display_name": "Semiconductor materials and devices", + "ipc_label": "STATIC STORES semiconductor memory devices H10B", + "match_score": 0.61 + }, + "G16C": { + "topic_id": "https://openalex.org/T10192", + "topic_display_name": "Catalytic Processes in Materials Science", + "ipc_label": "COMPUTATIONAL CHEMISTRYCHEMOINFORMATICSCOMPUTATIONAL MATERIALS SCIENCE", + "match_score": 0.527 + }, + "G16H": { + "topic_id": "https://openalex.org/T11773", + "topic_display_name": "Healthcare Operations and Scheduling Optimization", + "ipc_label": "HEALTHCARE INFORMATICS, i.e. INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR THE HANDLING OR PROCESSING OF MEDICAL OR HEALTHCARE DATA", + "match_score": 0.384 + }, + "G16Y": { + "topic_id": "https://openalex.org/T13952", + "topic_display_name": "Information Technology and Learning", + "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]", + "match_score": 0.508 + }, + "G16Z": { + "topic_id": "https://openalex.org/T12734", + "topic_display_name": "Information Systems and Technology Applications", + "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.456 + }, + "G21B": { + "topic_id": "https://openalex.org/T10592", + "topic_display_name": "Fusion materials and technologies", + "ipc_label": "FUSION REACTORS uncontrolled reactors G21J", + "match_score": 0.48 + }, + "G21C": { + "topic_id": "https://openalex.org/T10808", + "topic_display_name": "Electric and Hybrid Vehicle Technologies", + "ipc_label": "NUCLEAR REACTORS fusion reactors, hybrid fission-fusion reactors G21B; nuclear explosives G21J", + "match_score": 0.388 + }, + "G21D": { + "topic_id": "https://openalex.org/T12295", + "topic_display_name": "Foucault, Power, and Ethics", + "ipc_label": "NUCLEAR POWER PLANT", + "match_score": 0.565 + }, + "G21J": { + "topic_id": "https://openalex.org/T12405", + "topic_display_name": "Characterization and Applications of Magnetic Nanoparticles", + "ipc_label": "NUCLEAR EXPLOSIVESAPPLICATIONS THEREOF electric or magnetic analogue computers, e.g. simulators, for nuclear physics G06G7/54", + "match_score": 0.413 + }, + "G99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "H01C": { + "topic_id": "https://openalex.org/T12454", + "topic_display_name": "European Political History Analysis", + "ipc_label": "RESISTORS", + "match_score": 0.625 + }, + "H01J": { + "topic_id": "https://openalex.org/T12495", + "topic_display_name": "Electrostatic Discharge in Electronics", + "ipc_label": "ELECTRIC DISCHARGE TUBES OR DISCHARGE LAMPS spark-gaps H01T; arc lamps with consumable electrodes H05B; particle accelerators H05H", + "match_score": 0.381 + }, + "H01M": { + "topic_id": "https://openalex.org/T12495", + "topic_display_name": "Electrostatic Discharge in Electronics", + "ipc_label": "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE DIRECT CONVERSION OF CHEMICAL ENERGY INTO ELECTRICAL ENERGY", + "match_score": 0.383 + }, + "H01P": { + "topic_id": "https://openalex.org/T11429", + "topic_display_name": "Semiconductor Lasers and Optical Devices", + "ipc_label": "WAVEGUIDESRESONATORS, LINES, OR OTHER DEVICES OF THE WAVEGUIDE TYPE operating at optical frequencies G02B", + "match_score": 0.4 + }, + "H01Q": { + "topic_id": "https://openalex.org/T10579", + "topic_display_name": "Cognitive Radio Networks and Spectrum Sensing", + "ipc_label": "ANTENNAS, i.e. RADIO AERIALS radiators or antennas for microwave heating H05B6/72", + "match_score": 0.397 + }, + "H02B": { + "topic_id": "https://openalex.org/T10968", + "topic_display_name": "Statistical Distribution Estimation and Applications", + "ipc_label": "BOARDS, SUBSTATIONS OR SWITCHING ARRANGEMENTS FOR THE SUPPLY OR DISTRIBUTION OF ELECTRIC POWER", + "match_score": 0.411 + }, + "H02G": { + "topic_id": "https://openalex.org/T10607", + "topic_display_name": "Magnetic and transport properties of perovskites and related materials", + "ipc_label": "INSTALLATION OF ELECTRIC CABLES OR LINES, OR OF COMBINED OPTICAL AND ELECTRIC CABLES OR LINES", + "match_score": 0.444 + }, + "H02J": { + "topic_id": "https://openalex.org/T12111", + "topic_display_name": "Industrial Vision Systems and Defect Detection", + "ipc_label": "CIRCUIT ARRANGEMENTS OR SYSTEMS FOR SUPPLYING OR DISTRIBUTING ELECTRIC POWERSYSTEMS FOR STORING ELECTRIC ENERGY", + "match_score": 0.369 + }, + "H02N": { + "topic_id": "https://openalex.org/T10768", + "topic_display_name": "Electric Vehicles and Infrastructure", + "ipc_label": "ELECTRIC MACHINES NOT OTHERWISE PROVIDED FOR", + "match_score": 0.475 + }, + "H03C": { + "topic_id": "https://openalex.org/T10030", + "topic_display_name": "Electrocatalysts for Energy Conversion", + "ipc_label": "MODULATION masers or lasers H01S; coding, decoding or code conversion H03M", + "match_score": 0.429 + }, + "H03G": { + "topic_id": "https://openalex.org/T13924", + "topic_display_name": "Internet of Things and Social Network Interactions", + "ipc_label": "CONTROL OF AMPLIFICATION impedance networks, e.g. attenuators, H03H; control of transmission in lines H04B3/04", + "match_score": 0.375 + }, + "H03J": { + "topic_id": "https://openalex.org/T14117", + "topic_display_name": "Integrated Circuits and Semiconductor Failure Analysis", + "ipc_label": "TUNING RESONANT CIRCUITSSELECTING RESONANT CIRCUITS", + "match_score": 0.476 + }, + "H03L": { + "topic_id": "https://openalex.org/T13257", + "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", + "ipc_label": "AUTOMATIC CONTROL, STARTING, SYNCHRONISATION, OR STABILISATION OF GENERATORS OF ELECTRONIC OSCILLATIONS OR PULSES of dynamo-electric generators H02P", + "match_score": 0.355 + }, + "H04B": { + "topic_id": "https://openalex.org/T12804", + "topic_display_name": "Thermal Analysis in Power Transmission", + "ipc_label": "TRANSMISSION", + "match_score": 1.0 + }, + "H04H": { + "topic_id": "https://openalex.org/T12593", + "topic_display_name": "Communication in Education and Healthcare", + "ipc_label": "BROADCAST COMMUNICATION multiplex communication H04J; pictorial communication aspects of broadcast systems H04N", + "match_score": 0.408 + }, + "H04K": { + "topic_id": "https://openalex.org/T13317", + "topic_display_name": "Media, Communication, and Education", + "ipc_label": "SECRET COMMUNICATIONJAMMING OF COMMUNICATION", + "match_score": 0.633 + }, + "H04L": { + "topic_id": "https://openalex.org/T12607", + "topic_display_name": "Personal Information Management and User Behavior", + "ipc_label": "TRANSMISSION OF DIGITAL INFORMATION, e.g. TELEGRAPHIC COMMUNICATION arrangements common to telegraphic and telephonic communication H04M", + "match_score": 0.422 + }, + "H04M": { + "topic_id": "https://openalex.org/T13905", + "topic_display_name": "Telecommunications and Broadcasting Technologies", + "ipc_label": "TELEPHONIC COMMUNICATION circuits for controlling other apparatus via a telephone cable and not involving telephone switching apparatus G08", + "match_score": 0.374 + }, + "H04N": { + "topic_id": "https://openalex.org/T13317", + "topic_display_name": "Media, Communication, and Education", + "ipc_label": "PICTORIAL COMMUNICATION, e.g. TELEVISION", + "match_score": 0.613 + }, + "H04Q": { + "topic_id": "https://openalex.org/T10575", + "topic_display_name": "Wireless Communication Networks Research", + "ipc_label": "SELECTING switches, relays, selectors H01H; wireless communication networks H04W", + "match_score": 0.55 + }, + "H04S": { + "topic_id": "https://openalex.org/T11575", + "topic_display_name": "Nonlinear Photonic Systems", + "ipc_label": "STEREOPHONIC SYSTEMS", + "match_score": 0.696 + }, + "H04T": { + "topic_id": "https://openalex.org/T11121", + "topic_display_name": "Public Relations and Crisis Communication", + "ipc_label": "INDEXING SCHEME RELATING TO STANDARDS FOR ELECTRIC COMMUNICATION TECHNIQUE CLASS H04", + "match_score": 0.512 + }, + "H04W": { + "topic_id": "https://openalex.org/T10575", + "topic_display_name": "Wireless Communication Networks Research", + "ipc_label": "WIRELESS COMMUNICATION NETWORKS broadcast communication H04H; communication systems using wireless links for non-selective communication, e.g. wireless extensions H04M1/72", + "match_score": 0.36 + }, + "H05B": { + "topic_id": "https://openalex.org/T13093", + "topic_display_name": "Electric Power Systems and Control", + "ipc_label": "ELECTRIC HEATINGELECTRIC LIGHT SOURCES NOT OTHERWISE PROVIDED FORCIRCUIT ARRANGEMENTS FOR ELECTRIC LIGHT SOURCES, IN GENERAL", + "match_score": 0.36 + }, + "H10B": { + "topic_id": "https://openalex.org/T10299", + "topic_display_name": "Photonic and Optical Devices", + "ipc_label": "ELECTRONIC MEMORY DEVICES", + "match_score": 0.667 + }, + "H10K": { + "topic_id": "https://openalex.org/T10045", + "topic_display_name": "Organic Electronics and Photovoltaics", + "ipc_label": "ORGANIC ELECTRIC SOLID-STATE DEVICES", + "match_score": 0.658 + }, + "H10N": { + "topic_id": "https://openalex.org/T10768", + "topic_display_name": "Electric Vehicles and Infrastructure", + "ipc_label": "ELECTRIC SOLID-STATE DEVICES NOT OTHERWISE PROVIDED FOR", + "match_score": 0.44 + }, + "H99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "Y02A": { + "topic_id": "https://openalex.org/T10895", + "topic_display_name": "Species Distribution and Climate Change", + "ipc_label": "TECHNOLOGIES FOR ADAPTATION TO CLIMATE CHANGE", + "match_score": 0.643 + }, + "Y02B": { + "topic_id": "https://openalex.org/T13734", + "topic_display_name": "Advanced Computational Techniques and Applications", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO BUILDINGS, e.g. HOUSING, HOUSE APPLIANCES OR RELATED END-USER APPLICATIONS", + "match_score": 0.425 + }, + "Y02C": { + "topic_id": "https://openalex.org/T10945", + "topic_display_name": "Lysosomal Storage Disorders Research", + "ipc_label": "CAPTURE, STORAGE, SEQUESTRATION OR DISPOSAL OF GREENHOUSE GASES [GHG]", + "match_score": 0.419 + }, + "Y02P": { + "topic_id": "https://openalex.org/T11488", + "topic_display_name": "Climate Change Communication and Perception", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES IN THE PRODUCTION OR PROCESSING OF GOODS", + "match_score": 0.525 + }, + "Y02T": { + "topic_id": "https://openalex.org/T11488", + "topic_display_name": "Climate Change Communication and Perception", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO TRANSPORTATION", + "match_score": 0.598 + }, + "Y02W": { + "topic_id": "https://openalex.org/T11404", + "topic_display_name": "Irrigation Practices and Water Management", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO WASTEWATER TREATMENT OR WASTE MANAGEMENT", + "match_score": 0.504 + }, + "Y10S": { + "topic_id": "https://openalex.org/T13332", + "topic_display_name": "Historical Studies on Reproduction, Gender, Health, and Societal Changes", + "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER USPC CROSS-REFERENCE ART COLLECTIONS [XRACs] AND DIGESTS", + "match_score": 0.412 + }, + "Y10T": { + "topic_id": "https://openalex.org/T10885", + "topic_display_name": "Gene expression and cancer classification", + "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER US CLASSIFICATION", + "match_score": 0.484 + } + }, + "subclass": { + "A01D": { + "topic_id": "https://openalex.org/T13896", + "topic_display_name": "Health Services Management and Policy", + "ipc_label": "HARVESTINGMOWING", + "match_score": 0.412 + }, + "A01H": { + "topic_id": "https://openalex.org/T10442", + "topic_display_name": "Knee injuries and reconstruction techniques", + "ipc_label": "NEW PLANTS OR NON-TRANSGENIC PROCESSES FOR OBTAINING THEMPLANT REPRODUCTION BY TISSUE CULTURE TECHNIQUES", + "match_score": 0.435 + }, + "A01J": { + "topic_id": "https://openalex.org/T11386", + "topic_display_name": "Bee Products Chemical Analysis", + "ipc_label": "MANUFACTURE OF DAIRY PRODUCTS for chemical matters, see subclass A23C", + "match_score": 0.465 + }, + "A01L": { + "topic_id": "https://openalex.org/T11905", + "topic_display_name": "Veterinary Pharmacology and Anesthesia", + "ipc_label": "SHOEING OF ANIMALS", + "match_score": 0.581 + }, + "A01P": { + "topic_id": "https://openalex.org/T14099", + "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", + "ipc_label": "BIOCIDAL, PEST REPELLANT, PEST ATTRACTANT OR PLANT GROWTH REGULATORY ACTIVITY OF CHEMICAL COMPOUNDS OR PREPARATIONS", + "match_score": 0.386 + }, + "A21C": { + "topic_id": "https://openalex.org/T12282", + "topic_display_name": "Mineral Processing and Grinding", + "ipc_label": "MACHINES OR EQUIPMENT FOR MAKING OR PROCESSING DOUGHSHANDLING BAKED ARTICLES MADE FROM DOUGH", + "match_score": 0.39 + }, + "A22B": { + "topic_id": "https://openalex.org/T13366", + "topic_display_name": "Accounting Theory and Financial Reporting", + "ipc_label": "SLAUGHTERING", + "match_score": 0.545 + }, + "A23K": { + "topic_id": "https://openalex.org/T12181", + "topic_display_name": "Agricultural and Biological Research", + "ipc_label": "FODDER", + "match_score": 0.444 + }, + "A23Y": { + "topic_id": "https://openalex.org/T12388", + "topic_display_name": "Identification and Quantification in Food", + "ipc_label": "INDEXING SCHEME RELATING TO LACTIC OR PROPIONIC ACID BACTERIA USED IN FOODSTUFFS OR FOOD PREPARATION", + "match_score": 0.369 + }, + "A24C": { + "topic_id": "https://openalex.org/T13832", + "topic_display_name": "Advanced Decision-Making Techniques", + "ipc_label": "MACHINES FOR MAKING CIGARS OR CIGARETTES", + "match_score": 0.475 + }, + "A41B": { + "topic_id": "https://openalex.org/T13368", + "topic_display_name": "University Challenges and Reforms", + "ipc_label": "SHIRTSUNDERWEARBABY LINENHANDKERCHIEFS", + "match_score": 0.451 + }, + "A41C": { + "topic_id": "https://openalex.org/T14190", + "topic_display_name": "Military history and social perspectives", + "ipc_label": "CORSETSBRASSIERES", + "match_score": 0.485 + }, + "A41D": { + "topic_id": "https://openalex.org/T13272", + "topic_display_name": "Psychological Treatments and Assessments", + "ipc_label": "OUTERWEARPROTECTIVE GARMENTSACCESSORIES", + "match_score": 0.43 + }, + "A41F": { + "topic_id": "https://openalex.org/T13129", + "topic_display_name": "Material Properties and Applications", + "ipc_label": "GARMENT FASTENINGSSUSPENDERS", + "match_score": 0.491 + }, + "A41G": { + "topic_id": "https://openalex.org/T13734", + "topic_display_name": "Advanced Computational Techniques and Applications", + "ipc_label": "ARTIFICIAL FLOWERSWIGSMASKSFEATHERS", + "match_score": 0.552 + }, + "A42C": { + "topic_id": "https://openalex.org/T11159", + "topic_display_name": "Manufacturing Process and Optimization", + "ipc_label": "MANUFACTURING OR TRIMMING HEAD COVERINGS, e.g. HATS", + "match_score": 0.494 + }, + "A43B": { + "topic_id": "https://openalex.org/T13232", + "topic_display_name": "Laser-Ablation Synthesis of Nanoparticles", + "ipc_label": "CHARACTERISTIC FEATURES OF FOOTWEARPARTS OF FOOTWEAR", + "match_score": 0.387 + }, + "A43C": { + "topic_id": "https://openalex.org/T13288", + "topic_display_name": "Banking, Crisis Management, COVID-19 Impact", + "ipc_label": "FASTENINGS OR ATTACHMENTS OF FOOTWEARLACES IN GENERAL", + "match_score": 0.375 + }, + "A43D": { + "topic_id": "https://openalex.org/T13290", + "topic_display_name": "Diverse Industrial Engineering Technologies", + "ipc_label": "MACHINES, TOOLS, EQUIPMENT OR METHODS FOR MANUFACTURING OR REPAIRING FOOTWEAR", + "match_score": 0.462 + }, + "A44C": { + "topic_id": "https://openalex.org/T12607", + "topic_display_name": "Personal Information Management and User Behavior", + "ipc_label": "PERSONAL ADORNMENTS, e.g. JEWELLERYCOINS", + "match_score": 0.449 + }, + "A44D": { + "topic_id": "https://openalex.org/T11334", + "topic_display_name": "Psychosomatic Disorders and Their Treatments", + "ipc_label": "INDEXING SCHEME RELATING TO BUTTONS, PINS, BUCKLES OR SLIDE FASTENERS, AND TO JEWELLERY, BRACELETS OR OTHER PERSONAL ADORNMENTS", + "match_score": 0.374 + }, + "A45C": { + "topic_id": "https://openalex.org/T10413", + "topic_display_name": "High-pressure geophysics and materials", + "ipc_label": "PURSESLUGGAGEHAND CARRIED BAGS", + "match_score": 0.471 + }, + "A45F": { + "topic_id": "https://openalex.org/T11867", + "topic_display_name": "Traumatic Ocular and Foreign Body Injuries", + "ipc_label": "TRAVELLING OR CAMP EQUIPMENT: SACKS OR PACKS CARRIED ON THE BODY", + "match_score": 0.358 + }, + "A46B": { + "topic_id": "https://openalex.org/T13398", + "topic_display_name": "Data Analysis with R", + "ipc_label": "BRUSHES handles not integral with brushware B25G", + "match_score": 0.353 + }, + "A46D": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "MANUFACTURE OF BRUSHES", + "match_score": 0.455 + }, + "A47B": { + "topic_id": "https://openalex.org/T14133", + "topic_display_name": "Border Security and International Relations", + "ipc_label": "TABLESDESKSOFFICE FURNITURECABINETSDRAWERSGENERAL DETAILS OF FURNITURE furniture jointing F16B", + "match_score": 0.35 + }, + "A47C": { + "topic_id": "https://openalex.org/T10495", + "topic_display_name": "Catalysts for Methane Reforming", + "ipc_label": "CHAIRS seats specially adapted for vehicles B60N2/00SOFASBEDS upholstery in general B68G", + "match_score": 0.353 + }, + "A47G": { + "topic_id": "https://openalex.org/T14160", + "topic_display_name": "Water management and technologies", + "ipc_label": "HOUSEHOLD OR TABLE EQUIPMENT book-ends A47B5/00; knives B26B", + "match_score": 0.366 + }, + "A47J": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "KITCHEN EQUIPMENTCOFFEE MILLSSPICE MILLSAPPARATUS FOR MAKING BEVERAGES", + "match_score": 0.378 + }, + "A61D": { + "topic_id": "https://openalex.org/T14236", + "topic_display_name": "Educational Tools and Methods", + "ipc_label": "VETERINARY INSTRUMENTS, IMPLEMENTS, TOOLS, OR METHODS", + "match_score": 0.512 + }, + "A61P": { + "topic_id": "https://openalex.org/T12685", + "topic_display_name": "Phytochemical compounds biological activities", + "ipc_label": "SPECIFIC THERAPEUTIC ACTIVITY OF CHEMICAL COMPOUNDS OR MEDICINAL PREPARATIONS", + "match_score": 0.525 + }, + "A61Q": { + "topic_id": "https://openalex.org/T10576", + "topic_display_name": "Opioid Use Disorder Treatment", + "ipc_label": "SPECIFIC USE OF COSMETICS OR SIMILAR TOILETRY PREPARATIONS", + "match_score": 0.437 + }, + "A62D": { + "topic_id": "https://openalex.org/T11802", + "topic_display_name": "Chemical Looping and Thermochemical Processes", + "ipc_label": "CHEMICAL MEANS FOR EXTINGUISHING FIRES OR FOR COMBATING OR PROTECTING AGAINST HARMFUL CHEMICAL AGENTSCHEMICAL MATERIALS FOR USE IN BREATHING APPARATUS", + "match_score": 0.369 + }, + "A63H": { + "topic_id": "https://openalex.org/T12105", + "topic_display_name": "Hygrothermal properties of building materials", + "ipc_label": "TOYS, e.g. TOPS, DOLLS, HOOPS OR BUILDING BLOCKS", + "match_score": 0.409 + }, + "A99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "B01B": { + "topic_id": "https://openalex.org/T11900", + "topic_display_name": "Fungal Plant Pathogen Control", + "ipc_label": "BOILINGBOILING APPARATUS ; EVAPORATION; EVAPORATION APPARATUS", + "match_score": 0.381 + }, + "B01J": { + "topic_id": "https://openalex.org/T13104", + "topic_display_name": "Chemical and Physical Properties of Materials", + "ipc_label": "CHEMICAL OR PHYSICAL PROCESSES, e.g. CATALYSIS OR COLLOID CHEMISTRYTHEIR RELEVANT APPARATUS", + "match_score": 0.471 + }, + "B01L": { + "topic_id": "https://openalex.org/T13104", + "topic_display_name": "Chemical and Physical Properties of Materials", + "ipc_label": "CHEMICAL OR PHYSICAL LABORATORY APPARATUS FOR GENERAL USE", + "match_score": 0.549 + }, + "B03B": { + "topic_id": "https://openalex.org/T11808", + "topic_display_name": "Superconducting Materials and Applications", + "ipc_label": "SEPARATING SOLID MATERIALS USING LIQUIDS OR USING PNEUMATIC TABLES OR JIGS", + "match_score": 0.448 + }, + "B09B": { + "topic_id": "https://openalex.org/T11108", + "topic_display_name": "Municipal Solid Waste Management", + "ipc_label": "DISPOSAL OF SOLID WASTE", + "match_score": 0.667 + }, + "B21G": { + "topic_id": "https://openalex.org/T10377", + "topic_display_name": "Metal and Thin Film Mechanics", + "ipc_label": "MAKING NEEDLES, PINS OR NAILS OF METAL", + "match_score": 0.4 + }, + "B22C": { + "topic_id": "https://openalex.org/T11853", + "topic_display_name": "Semiconductor materials and interfaces", + "ipc_label": "FOUNDRY MOULDING moulding refractory materials in general B28B", + "match_score": 0.48 + }, + "B23B": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "TURNINGBORING arrangements for copying or controlling B23Q", + "match_score": 0.424 + }, + "B24C": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "ABRASIVE OR RELATED BLASTING WITH PARTICULATE MATERIAL", + "match_score": 0.469 + }, + "B25H": { + "topic_id": "https://openalex.org/T10488", + "topic_display_name": "Nanocomposite Films for Food Packaging", + "ipc_label": "WORKSHOP EQUIPMENT, e.g. FOR MARKING-OUT WORKSTORAGE MEANS FOR WORKSHOPS storing or packaging B65", + "match_score": 0.356 + }, + "B27H": { + "topic_id": "https://openalex.org/T14076", + "topic_display_name": "Material Properties and Failure Mechanisms", + "ipc_label": "BENDING WOOD OR SIMILAR MATERIALCOOPERAGEMAKING WHEELS FROM WOOD OR SIMILAR MATERIAL", + "match_score": 0.381 + }, + "B27J": { + "topic_id": "https://openalex.org/T10219", + "topic_display_name": "Mechanical Behavior of Composites", + "ipc_label": "MECHANICAL WORKING OF CANE, CORK, OR SIMILAR MATERIALS", + "match_score": 0.575 + }, + "B28D": { + "topic_id": "https://openalex.org/T10811", + "topic_display_name": "Hydrogen Storage and Materials", + "ipc_label": "WORKING STONE OR STONE-LIKE MATERIALS", + "match_score": 0.567 + }, + "B29L": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS B29C, RELATING TO PARTICULAR ARTICLES", + "match_score": 0.393 + }, + "B41F": { + "topic_id": "https://openalex.org/T11523", + "topic_display_name": "Nanomaterials and Printing Technologies", + "ipc_label": "PRINTING MACHINES OR PRESSES manifolding devices or office printing machines B41L", + "match_score": 0.383 + }, + "B41P": { + "topic_id": "https://openalex.org/T13557", + "topic_display_name": "Environmental and sustainability education", + "ipc_label": "INDEXING SCHEME RELATING TO PRINTING, LINING MACHINES, TYPEWRITERS, AND TO STAMPS", + "match_score": 0.42 + }, + "B42P": { + "topic_id": "https://openalex.org/T11877", + "topic_display_name": "Iron oxide chemistry and applications", + "ipc_label": "INDEXING SCHEME RELATING TO BOOKS, FILING APPLIANCES OR THE LIKE", + "match_score": 0.416 + }, + "B44F": { + "topic_id": "https://openalex.org/T12174", + "topic_display_name": "Hospital Admissions and Outcomes", + "ipc_label": "SPECIAL DESIGNS OR PICTURES", + "match_score": 0.542 + }, + "B60C": { + "topic_id": "https://openalex.org/T12641", + "topic_display_name": "Historical and socio-economic studies of Spain and related regions", + "ipc_label": "VEHICLE TYRESTYRE INFLATIONTYRE CHANGINGCONNECTING VALVES TO INFLATABLE ELASTIC BODIES IN GENERALDEVICES OR ARRANGEMENTS RELATED TO TYRES", + "match_score": 0.384 + }, + "B60D": { + "topic_id": "https://openalex.org/T10829", + "topic_display_name": "Interconnection Networks and Systems", + "ipc_label": "VEHICLE CONNECTIONS components of brake systems B60T17/04", + "match_score": 0.473 + }, + "B60F": { + "topic_id": "https://openalex.org/T14022", + "topic_display_name": "Cultural and Religious Practices in Indonesia", + "ipc_label": "VEHICLES FOR USE BOTH ON RAIL AND ON ROADAMPHIBIOUS OR LIKE VEHICLESCONVERTIBLE VEHICLES air-cushion vehicles B60V", + "match_score": 0.377 + }, + "B60G": { + "topic_id": "https://openalex.org/T10805", + "topic_display_name": "Vehicle Dynamics and Control Systems", + "ipc_label": "VEHICLE SUSPENSION ARRANGEMENTS air-cushion vehicles B60V; cycle suspensions B62K25/00", + "match_score": 0.361 + }, + "B60H": { + "topic_id": "https://openalex.org/T10558", + "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", + "ipc_label": "ARRANGEMENTS OF HEATING, COOLING, VENTILATING OR OTHER AIR-TREATING DEVICES SPECIALLY ADAPTED FOR PASSENGER OR GOODS SPACES OF VEHICLES", + "match_score": 0.366 + }, + "B60Q": { + "topic_id": "https://openalex.org/T10558", + "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", + "ipc_label": "ARRANGEMENT OF SIGNALLING OR LIGHTING DEVICES, THE MOUNTING OR SUPPORTING THEREOF OR CIRCUITS THEREFOR, FOR VEHICLES IN GENERAL", + "match_score": 0.415 + }, + "B60R": { + "topic_id": "https://openalex.org/T12707", + "topic_display_name": "Vehicle License Plate Recognition", + "ipc_label": "VEHICLES, VEHICLE FITTINGS, OR VEHICLE PARTS, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.381 + }, + "B60V": { + "topic_id": "https://openalex.org/T11002", + "topic_display_name": "Indoor Air Quality and Microbial Exposure", + "ipc_label": "AIR-CUSHION VEHICLES", + "match_score": 0.393 + }, + "B60Y": { + "topic_id": "https://openalex.org/T12898", + "topic_display_name": "Induction Heating and Inverter Technology", + "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS CROSS-CUTTING VEHICLE TECHNOLOGY", + "match_score": 0.569 + }, + "B61D": { + "topic_id": "https://openalex.org/T12271", + "topic_display_name": "Renewable energy and sustainable power systems", + "ipc_label": "BODY DETAILS OR KINDS OF RAILWAY VEHICLES vehicles in general B60; adaptation of vehicles to special systems B61B; underframes B61F", + "match_score": 0.35 + }, + "B61G": { + "topic_id": "https://openalex.org/T14049", + "topic_display_name": "Plant and Fungal Species Descriptions", + "ipc_label": "COUPLINGSDRAUGHT AND BUFFING APPLIANCES vehicle connections in general B60D", + "match_score": 0.446 + }, + "B61J": { + "topic_id": "https://openalex.org/T10757", + "topic_display_name": "Geographic Information Systems Studies", + "ipc_label": "SHIFTING OR SHUNTING OF RAIL VEHICLES shifting vehicles in general B60S; marshalling systems B61B", + "match_score": 0.37 + }, + "B62C": { + "topic_id": "https://openalex.org/T13551", + "topic_display_name": "Biochemical effects in animals", + "ipc_label": "VEHICLES DRAWN BY ANIMALS", + "match_score": 0.582 + }, + "B63J": { + "topic_id": "https://openalex.org/T11427", + "topic_display_name": "Elbow and Forearm Trauma Treatment", + "ipc_label": "AUXILIARIES ON VESSELS", + "match_score": 0.444 + }, + "B64B": { + "topic_id": "https://openalex.org/T12916", + "topic_display_name": "COVID-19 impact on air quality", + "ipc_label": "LIGHTER-THAN AIR AIRCRAFT", + "match_score": 0.4 + }, + "B64C": { + "topic_id": "https://openalex.org/T10647", + "topic_display_name": "Coastal and Marine Dynamics", + "ipc_label": "AEROPLANESHELICOPTERS", + "match_score": 0.49 + }, + "B64U": { + "topic_id": "https://openalex.org/T11192", + "topic_display_name": "Underwater Vehicles and Communication Systems", + "ipc_label": "UNMANNED AERIAL VEHICLES [UAV]EQUIPMENT THEREFOR", + "match_score": 0.43 + }, + "B65H": { + "topic_id": "https://openalex.org/T13917", + "topic_display_name": "Engineering and Material Science Research", + "ipc_label": "HANDLING THIN OR FILAMENTARY MATERIAL, e.g. SHEETS, WEBS, CABLES", + "match_score": 0.419 + }, + "B68B": { + "topic_id": "https://openalex.org/T12617", + "topic_display_name": "Energy, Environment, and Transportation Policies", + "ipc_label": "HARNESSDEVICES USED IN CONNECTION THEREWITHWHIPS OR THE LIKE", + "match_score": 0.389 + }, + "B68C": { + "topic_id": "https://openalex.org/T13896", + "topic_display_name": "Health Services Management and Policy", + "ipc_label": "SADDLESSTIRRUPS", + "match_score": 0.424 + }, + "B81B": { + "topic_id": "https://openalex.org/T12111", + "topic_display_name": "Industrial Vision Systems and Defect Detection", + "ipc_label": "MICROSTRUCTURAL DEVICES OR SYSTEMS, e.g. MICROMECHANICAL DEVICES piezo-electric, electrostrictive or magnetostrictive elements per se H10N30/00", + "match_score": 0.37 + }, + "B82Y": { + "topic_id": "https://openalex.org/T11169", + "topic_display_name": "Silicon Nanostructures and Photoluminescence", + "ipc_label": "SPECIFIC USES OR APPLICATIONS OF NANOSTRUCTURESMEASUREMENT OR ANALYSIS OF NANOSTRUCTURESMANUFACTURE OR TREATMENT OF NANOSTRUCTURES", + "match_score": 0.402 + }, + "B99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "C01B": { + "topic_id": "https://openalex.org/T12458", + "topic_display_name": "Organometallic Compounds Synthesis and Characterization", + "ipc_label": "NON-METALLIC ELEMENTSCOMPOUNDS THEREOF; METALLOIDS OR COMPOUNDS THEREOF NOT COVERED BY SUBCLASS C01C", + "match_score": 0.4 + }, + "C01P": { + "topic_id": "https://openalex.org/T12410", + "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", + "ipc_label": "INDEXING SCHEME RELATING TO STRUCTURAL AND PHYSICAL ASPECTS OF SOLID INORGANIC COMPOUNDS", + "match_score": 0.658 + }, + "C03B": { + "topic_id": "https://openalex.org/T10705", + "topic_display_name": "Additive Manufacturing Materials and Processes", + "ipc_label": "MANUFACTURE, SHAPING, OR SUPPLEMENTARY PROCESSES", + "match_score": 0.574 + }, + "C05B": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "PHOSPHATIC FERTILISERS", + "match_score": 0.5 + }, + "C05C": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "NITROGENOUS FERTILISERS", + "match_score": 0.444 + }, + "C05D": { + "topic_id": "https://openalex.org/T10973", + "topic_display_name": "Radioactive element chemistry and processing", + "ipc_label": "INORGANIC FERTILISERS NOT COVERED BY SUBCLASSES C05B, C05CFERTILISERS PRODUCING CARBON DIOXIDE", + "match_score": 0.362 + }, + "C06F": { + "topic_id": "https://openalex.org/T13862", + "topic_display_name": "Soil, Finite Element Methods", + "ipc_label": "MATCHESMANUFACTURE OF MATCHES", + "match_score": 0.588 + }, + "C07B": { + "topic_id": "https://openalex.org/T14099", + "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", + "ipc_label": "GENERAL METHODS OF ORGANIC CHEMISTRYAPPARATUS THEREFOR preparation of carboxylic acid esters by telomerisation C07C67/47; telomerisation C08F", + "match_score": 0.355 + }, + "C07C": { + "topic_id": "https://openalex.org/T13208", + "topic_display_name": "Synthesis of heterocyclic compounds", + "ipc_label": "ACYCLIC OR CARBOCYCLIC COMPOUNDS", + "match_score": 0.657 + }, + "C07D": { + "topic_id": "https://openalex.org/T13208", + "topic_display_name": "Synthesis of heterocyclic compounds", + "ipc_label": "HETEROCYCLIC COMPOUNDS macromolecular compounds C08", + "match_score": 0.512 + }, + "C07G": { + "topic_id": "https://openalex.org/T12055", + "topic_display_name": "Boron Compounds in Chemistry", + "ipc_label": "COMPOUNDS OF UNKNOWN CONSTITUTION", + "match_score": 0.492 + }, + "C07J": { + "topic_id": "https://openalex.org/T10310", + "topic_display_name": "Corrosion Behavior and Inhibition", + "ipc_label": "STEROIDS seco-steroids C07C", + "match_score": 0.455 + }, + "C08C": { + "topic_id": "https://openalex.org/T13037", + "topic_display_name": "Piperaceae Chemical and Biological Studies", + "ipc_label": "TREATMENT OR CHEMICAL MODIFICATION OF RUBBERS", + "match_score": 0.506 + }, + "C08F": { + "topic_id": "https://openalex.org/T13239", + "topic_display_name": "Phosphorus compounds and reactions", + "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED BY REACTIONS ONLY INVOLVING CARBON-TO-CARBON UNSATURATED BONDS", + "match_score": 0.4 + }, + "C08G": { + "topic_id": "https://openalex.org/T14459", + "topic_display_name": "Synthesis and Reactions of Organic Compounds", + "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED OTHERWISE THAN BY REACTIONS ONLY INVOLVING UNSATURATED CARBON-TO-CARBON BONDS", + "match_score": 0.387 + }, + "C09F": { + "topic_id": "https://openalex.org/T11823", + "topic_display_name": "Natural Resources and Economic Development", + "ipc_label": "NATURAL RESINSFRENCH POLISHDRYING-OILSDRIERS (SICCATIVES)TURPENTINE", + "match_score": 0.422 + }, + "C09G": { + "topic_id": "https://openalex.org/T12638", + "topic_display_name": "Pomegranate: compositions and health benefits", + "ipc_label": "POLISHING COMPOSITIONS French polish C09F11/00SKI WAXES", + "match_score": 0.42 + }, + "C09H": { + "topic_id": "https://openalex.org/T14032", + "topic_display_name": "History and International Relations", + "ipc_label": "PREPARATION OF GLUE OR GELATINE", + "match_score": 0.485 + }, + "C09K": { + "topic_id": "https://openalex.org/T10245", + "topic_display_name": "Metamaterials and Metasurfaces Applications", + "ipc_label": "MATERIALS FOR MISCELLANEOUS APPLICATIONS, NOT PROVIDED FOR ELSEWHERE", + "match_score": 0.523 + }, + "C10F": { + "topic_id": "https://openalex.org/T10650", + "topic_display_name": "Food Drying and Modeling", + "ipc_label": "DRYING OR WORKING-UP OF PEAT", + "match_score": 0.423 + }, + "C10H": { + "topic_id": "https://openalex.org/T12931", + "topic_display_name": "Educational Methods and Outcomes", + "ipc_label": "PRODUCTION OF ACETYLENE BY WET METHODS purification of acetylene C07C7/00", + "match_score": 0.457 + }, + "C10K": { + "topic_id": "https://openalex.org/T11848", + "topic_display_name": "Heme Oxygenase-1 and Carbon Monoxide", + "ipc_label": "PURIFYING OR MODIFYING THE CHEMICAL COMPOSITION OF COMBUSTIBLE GASES CONTAINING CARBON MONOXIDE", + "match_score": 0.412 + }, + "C10N": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS C10M RELATING TO LUBRICATING COMPOSITIONS", + "match_score": 0.397 + }, + "C11D": { + "topic_id": "https://openalex.org/T11869", + "topic_display_name": "Per- and polyfluoroalkyl substances research", + "ipc_label": "DETERGENT COMPOSITIONSUSE OF SINGLE SUBSTANCES AS DETERGENTSSOAP OR SOAP-MAKINGRESIN SOAPSRECOVERY OF GLYCEROL", + "match_score": 0.351 + }, + "C12J": { + "topic_id": "https://openalex.org/T12008", + "topic_display_name": "Solar-Powered Water Purification Methods", + "ipc_label": "VINEGARPREPARATION OR PURIFICATION THEREOF", + "match_score": 0.61 + }, + "C12R": { + "topic_id": "https://openalex.org/T10685", + "topic_display_name": "Viral-associated cancers and disorders", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES C12C - C12Q, RELATING TO MICROORGANISMS", + "match_score": 0.367 + }, + "C12Y": { + "topic_id": "https://openalex.org/T12770", + "topic_display_name": "Amino Acid Enzymes and Metabolism", + "ipc_label": "ENZYMES", + "match_score": 1.0 + }, + "C13B": { + "topic_id": "https://openalex.org/T12410", + "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", + "ipc_label": "PRODUCTION OF SUCROSEAPPARATUS SPECIALLY ADAPTED THEREFOR chemically synthesised sugars or sugar derivatives C07H; fermentation or enzyme-using processes for preparing compounds containing saccharide radicals C12P19/00", + "match_score": 0.351 + }, + "C21B": { + "topic_id": "https://openalex.org/T12301", + "topic_display_name": "Facial Nerve Paralysis Treatment and Research", + "ipc_label": "MANUFACTURE OF IRON OR STEEL preliminary treatment of ferrous ores or scrap C22B1/00; electric heating H05B", + "match_score": 0.368 + }, + "C22B": { + "topic_id": "https://openalex.org/T13652", + "topic_display_name": "Education and Social Development in Ukraine", + "ipc_label": "PRODUCTION AND REFINING OF METALS electrolytic C25PRETREATMENT OF RAW MATERIALS", + "match_score": 0.475 + }, + "C22C": { + "topic_id": "https://openalex.org/T11453", + "topic_display_name": "Diagnosis and Treatment of Venous Diseases", + "ipc_label": "ALLOYS flints C06C15/00; treatment of alloys C21D, C22F", + "match_score": 0.474 + }, + "C23D": { + "topic_id": "https://openalex.org/T13463", + "topic_display_name": "Nanoporous metals and alloys", + "ipc_label": "ENAMELLING OF, OR APPLYING A VITREOUS LAYER TO, METALS", + "match_score": 0.39 + }, + "C23G": { + "topic_id": "https://openalex.org/T14068", + "topic_display_name": "Organic and Inorganic Chemical Reactions", + "ipc_label": "CLEANING OR DE-GREASING OF METALLIC MATERIAL BY CHEMICAL METHODS OTHER THAN ELECTROLYSIS", + "match_score": 0.438 + }, + "C25C": { + "topic_id": "https://openalex.org/T10962", + "topic_display_name": "Thermodynamic properties of mixtures", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC PRODUCTION, RECOVERY OR REFINING OF METALSAPPARATUS THEREFOR", + "match_score": 0.378 + }, + "C25D": { + "topic_id": "https://openalex.org/T14382", + "topic_display_name": "Electrophoretic Deposition in Materials Science", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC OR ELECTROPHORETIC PRODUCTION OF COATINGSELECTROFORMINGAPPARATUS THEREFOR", + "match_score": 0.424 + }, + "C25F": { + "topic_id": "https://openalex.org/T11025", + "topic_display_name": "Nonlinear Optical Materials Research", + "ipc_label": "PROCESSES FOR THE ELECTROLYTIC REMOVAL OF MATERIALS FROM OBJECTSAPPARATUS THEREFOR", + "match_score": 0.458 + }, + "C99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "D01D": { + "topic_id": "https://openalex.org/T11416", + "topic_display_name": "Numerical methods for differential equations", + "ipc_label": "MECHANICAL METHODS OR APPARATUS IN THE MANUFACTURE OF ARTIFICIAL FILAMENTS, THREADS, FIBRES, BRISTLES OR RIBBONS", + "match_score": 0.397 + }, + "D02G": { + "topic_id": "https://openalex.org/T14192", + "topic_display_name": "Literature, Film, and Journalism Analysis", + "ipc_label": "CRIMPING OR CURLING FIBRES, FILAMENTS, THREADS, OR YARNSYARNS OR THREADS", + "match_score": 0.389 + }, + "D02H": { + "topic_id": "https://openalex.org/T13523", + "topic_display_name": "Mathematics, Computing, and Information Processing", + "ipc_label": "WARPING, BEAMING OR LEASING", + "match_score": 0.468 + }, + "D03C": { + "topic_id": "https://openalex.org/T12490", + "topic_display_name": "Software Engineering and Design Patterns", + "ipc_label": "SHEDDING MECHANISMSPATTERN CARDS OR CHAINSPUNCHING OF CARDSDESIGNING PATTERNS", + "match_score": 0.41 + }, + "D03D": { + "topic_id": "https://openalex.org/T13880", + "topic_display_name": "Innovative Education Methods and Tools", + "ipc_label": "WOVEN FABRICSMETHODS OF WEAVINGLOOMS", + "match_score": 0.459 + }, + "D03J": { + "topic_id": "https://openalex.org/T10262", + "topic_display_name": "Microwave Engineering and Waveguides", + "ipc_label": "AUXILIARY WEAVING APPARATUSWEAVERS' TOOLSSHUTTLES", + "match_score": 0.4 + }, + "D04B": { + "topic_id": "https://openalex.org/T13366", + "topic_display_name": "Accounting Theory and Financial Reporting", + "ipc_label": "KNITTING", + "match_score": 0.556 + }, + "D05C": { + "topic_id": "https://openalex.org/T13583", + "topic_display_name": "Jury Decision Making Processes", + "ipc_label": "EMBROIDERINGTUFTING making non-woven fabrics D04H; sewing D05B", + "match_score": 0.391 + }, + "D05D": { + "topic_id": "https://openalex.org/T14497", + "topic_display_name": "Social Issues and Policies in Latin America", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES D05B AND D05C, RELATING TO SEWING, EMBROIDERING AND TUFTING", + "match_score": 0.4 + }, + "D06C": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "FINISHING, DRESSING, TENTERING OR STRETCHING TEXTILE FABRICS", + "match_score": 0.484 + }, + "D06F": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "LAUNDERING, DRYING, IRONING, PRESSING OR FOLDING TEXTILE ARTICLES", + "match_score": 0.44 + }, + "D06H": { + "topic_id": "https://openalex.org/T11948", + "topic_display_name": "Machine Learning in Materials Science", + "ipc_label": "MARKING, INSPECTING, SEAMING OR SEVERING TEXTILE MATERIALS seaming by sewing D05B", + "match_score": 0.475 + }, + "D06P": { + "topic_id": "https://openalex.org/T11511", + "topic_display_name": "Dyeing and Modifying Textile Fibers", + "ipc_label": "DYEING OR PRINTING TEXTILESDYEING LEATHER, FURS OR SOLID MACROMOLECULAR SUBSTANCES IN ANY FORM", + "match_score": 0.372 + }, + "D10B": { + "topic_id": "https://openalex.org/T12078", + "topic_display_name": "Environmental remediation with nanomaterials", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBLASSES OF SECTION D, RELATING TO TEXTILES", + "match_score": 0.4 + }, + "D21B": { + "topic_id": "https://openalex.org/T11485", + "topic_display_name": "Gastrointestinal Tumor Research and Treatment", + "ipc_label": "FIBROUS RAW MATERIALS OR THEIR MECHANICAL TREATMENT", + "match_score": 0.562 + }, + "D21D": { + "topic_id": "https://openalex.org/T11071", + "topic_display_name": "Treatment of Major Depression", + "ipc_label": "TREATMENT OF THE MATERIALS BEFORE PASSING TO THE PAPER-MAKING MACHINE", + "match_score": 0.469 + }, + "D99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "E01F": { + "topic_id": "https://openalex.org/T14390", + "topic_display_name": "Real estate and construction management", + "ipc_label": "ADDITIONAL WORK, SUCH AS EQUIPPING ROADS OR THE CONSTRUCTION OF PLATFORMS, HELICOPTER LANDING STAGES, SIGNS, SNOW FENCES, OR THE LIKE", + "match_score": 0.36 + }, + "E02B": { + "topic_id": "https://openalex.org/T12907", + "topic_display_name": "Mechanical Engineering and Vibrations Research", + "ipc_label": "HYDRAULIC ENGINEERING ship-lifting E02C; dredging E02F", + "match_score": 0.5 + }, + "E02C": { + "topic_id": "https://openalex.org/T13253", + "topic_display_name": "Chemical Reactions and Mechanisms", + "ipc_label": "SHIP-LIFTING DEVICES OR MECHANISMS", + "match_score": 0.567 + }, + "E02D": { + "topic_id": "https://openalex.org/T12233", + "topic_display_name": "Geotechnical Engineering and Underground Structures", + "ipc_label": "FOUNDATIONSEXCAVATIONSEMBANKMENTS specially adapted for hydraulic engineering E02BUNDERGROUND OR UNDERWATER STRUCTURES tunnels, tunnelling, mining E21", + "match_score": 0.408 + }, + "E02F": { + "topic_id": "https://openalex.org/T13027", + "topic_display_name": "Applied Advanced Technologies", + "ipc_label": "DREDGINGSOIL-SHIFTING winning peat E21C49/00", + "match_score": 0.381 + }, + "E03D": { + "topic_id": "https://openalex.org/T14249", + "topic_display_name": "Water Quality Monitoring and Analysis", + "ipc_label": "WATER-CLOSETS OR URINALS WITH FLUSHING DEVICESFLUSHING VALVES THEREFOR", + "match_score": 0.355 + }, + "E03F": { + "topic_id": "https://openalex.org/T13675", + "topic_display_name": "Diffusion Coefficients in Liquids", + "ipc_label": "SEWERSCESSPOOLS", + "match_score": 0.444 + }, + "E05B": { + "topic_id": "https://openalex.org/T10859", + "topic_display_name": "Polymer Surface Interaction Studies", + "ipc_label": "LOCKSACCESSORIES THEREFORHANDCUFFS", + "match_score": 0.452 + }, + "E21C": { + "topic_id": "https://openalex.org/T11933", + "topic_display_name": "Mining and Resource Management", + "ipc_label": "MINING OR QUARRYING", + "match_score": 0.531 + }, + "E21F": { + "topic_id": "https://openalex.org/T10570", + "topic_display_name": "Drug Transport and Resistance Mechanisms", + "ipc_label": "SAFETY DEVICES, TRANSPORT, FILLING-UP, RESCUE, VENTILATION, OR DRAINING IN OR OF MINES OR TUNNELS", + "match_score": 0.38 + }, + "E99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "F01L": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "CYCLICALLY OPERATING VALVES FOR MACHINES OR ENGINES", + "match_score": 0.478 + }, + "F02F": { + "topic_id": "https://openalex.org/T10117", + "topic_display_name": "Advanced Combustion Engine Technologies", + "ipc_label": "CYLINDERS, PISTONS OR CASINGS, FOR COMBUSTION ENGINESARRANGEMENTS OF SEALINGS IN COMBUSTION ENGINES", + "match_score": 0.406 + }, + "F02M": { + "topic_id": "https://openalex.org/T13917", + "topic_display_name": "Engineering and Material Science Research", + "ipc_label": "SUPPLYING COMBUSTION ENGINES IN GENERAL WITH COMBUSTIBLE MIXTURES OR CONSTITUENTS THEREOF", + "match_score": 0.385 + }, + "F02N": { + "topic_id": "https://openalex.org/T10117", + "topic_display_name": "Advanced Combustion Engine Technologies", + "ipc_label": "STARTING OF COMBUSTION ENGINESSTARTING AIDS FOR SUCH ENGINES, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.441 + }, + "F03D": { + "topic_id": "https://openalex.org/T10504", + "topic_display_name": "Sensorless Control of Electric Motors", + "ipc_label": "WIND MOTORS", + "match_score": 0.5 + }, + "F03H": { + "topic_id": "https://openalex.org/T12661", + "topic_display_name": "Iterative Methods for Nonlinear Equations", + "ipc_label": "PRODUCING A REACTIVE PROPULSIVE THRUST, NOT OTHERWISE PROVIDED FOR from combustion products F02K", + "match_score": 0.35 + }, + "F16C": { + "topic_id": "https://openalex.org/T14144", + "topic_display_name": "Neurological Disease Mechanisms and Treatments", + "ipc_label": "SHAFTSFLEXIBLE SHAFTSELEMENTS OR CRANKSHAFT MECHANISMSROTARY BODIES OTHER THAN GEARING ELEMENTSBEARINGS", + "match_score": 0.376 + }, + "F16D": { + "topic_id": "https://openalex.org/T12240", + "topic_display_name": "Nanomaterials for catalytic reactions", + "ipc_label": "COUPLINGS FOR TRANSMITTING ROTATIONCLUTCHESBRAKES", + "match_score": 0.465 + }, + "F16F": { + "topic_id": "https://openalex.org/T10030", + "topic_display_name": "Electrocatalysts for Energy Conversion", + "ipc_label": "SPRINGSSHOCK-ABSORBERSMEANS FOR DAMPING VIBRATION", + "match_score": 0.437 + }, + "F16H": { + "topic_id": "https://openalex.org/T14252", + "topic_display_name": "Water and Wastewater Treatment", + "ipc_label": "GEARING", + "match_score": 0.667 + }, + "F16J": { + "topic_id": "https://openalex.org/T14353", + "topic_display_name": "Wireless Sensor Networks for Data Analysis", + "ipc_label": "PISTONS specially adapted for dampers F16F9/32CYLINDERSSEALINGS", + "match_score": 0.4 + }, + "F16L": { + "topic_id": "https://openalex.org/T11343", + "topic_display_name": "Power Transformer Diagnostics and Insulation", + "ipc_label": "PIPESJOINTS OR FITTINGS FOR PIPESSUPPORTS FOR PIPES, CABLES OR PROTECTIVE TUBINGMEANS FOR THERMAL INSULATION IN GENERAL", + "match_score": 0.356 + }, + "F16N": { + "topic_id": "https://openalex.org/T14075", + "topic_display_name": "Psychodrama and Leishmaniasis Studies", + "ipc_label": "LUBRICATING", + "match_score": 0.6 + }, + "F16P": { + "topic_id": "https://openalex.org/T11317", + "topic_display_name": "Fire dynamics and safety research", + "ipc_label": "SAFETY DEVICES IN GENERAL; SAFETY DEVICES FOR PRESSES", + "match_score": 0.488 + }, + "F16S": { + "topic_id": "https://openalex.org/T10915", + "topic_display_name": "Trace Elements in Health", + "ipc_label": "CONSTRUCTIONAL ELEMENTS IN GENERALSTRUCTURES BUILT-UP FROM SUCH ELEMENTS, IN GENERAL", + "match_score": 0.389 + }, + "F21L": { + "topic_id": "https://openalex.org/T13000", + "topic_display_name": "World Systems and Global Transformations", + "ipc_label": "LIGHTING DEVICES OR SYSTEMS THEREOF, BEING PORTABLE OR SPECIALLY ADAPTED FOR TRANSPORTATION", + "match_score": 0.427 + }, + "F21W": { + "topic_id": "https://openalex.org/T13257", + "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", + "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES F21K, F21L, F21S and F21V, RELATING TO USES OR APPLICATIONS OF LIGHTING DEVICES OR SYSTEMS", + "match_score": 0.383 + }, + "F22G": { + "topic_id": "https://openalex.org/T13960", + "topic_display_name": "Dietetics, Nutrition, and Education", + "ipc_label": "SUPERHEATING OF STEAM steam separating arrangements in boilers F22B37/26", + "match_score": 0.416 + }, + "F23D": { + "topic_id": "https://openalex.org/T11069", + "topic_display_name": "Testicular diseases and treatments", + "ipc_label": "BURNERS", + "match_score": 0.571 + }, + "F23G": { + "topic_id": "https://openalex.org/T14505", + "topic_display_name": "Natural Products and Applications", + "ipc_label": "CREMATION FURNACESCONSUMING WASTE PRODUCTS BY COMBUSTION", + "match_score": 0.472 + }, + "F23K": { + "topic_id": "https://openalex.org/T10806", + "topic_display_name": "Energetic Materials and Combustion", + "ipc_label": "FEEDING FUEL TO COMBUSTION APPARATUS fuel feeders specially adapted for fluidised bed combustion apparatus F23C10/22", + "match_score": 0.373 + }, + "F24S": { + "topic_id": "https://openalex.org/T10108", + "topic_display_name": "Electoral Systems and Political Participation", + "ipc_label": "SOLAR HEAT COLLECTORSSOLAR HEAT SYSTEMS for producing mechanical power from solar energy F03G6/00", + "match_score": 0.423 + }, + "F24T": { + "topic_id": "https://openalex.org/T11225", + "topic_display_name": "Geothermal Energy Systems and Applications", + "ipc_label": "GEOTHERMAL COLLECTORSGEOTHERMAL SYSTEMS", + "match_score": 0.667 + }, + "F24V": { + "topic_id": "https://openalex.org/T10171", + "topic_display_name": "Biofuel production and bioconversion", + "ipc_label": "COLLECTION, PRODUCTION OR USE OF HEAT NOT OTHERWISE PROVIDED FOR", + "match_score": 0.42 + }, + "F25B": { + "topic_id": "https://openalex.org/T13985", + "topic_display_name": "Enterprise Management and Information Systems", + "ipc_label": "REFRIGERATION MACHINES, PLANTS OR SYSTEMSCOMBINED HEATING AND REFRIGERATION SYSTEMSHEAT PUMP SYSTEMS", + "match_score": 0.414 + }, + "F25C": { + "topic_id": "https://openalex.org/T12544", + "topic_display_name": "Working Capital and Financial Performance", + "ipc_label": "PRODUCING, WORKING OR HANDLING ICE", + "match_score": 0.453 + }, + "F27M": { + "topic_id": "https://openalex.org/T10055", + "topic_display_name": "Diverse Aspects of Tourism Research", + "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS OF THE CHARGES OR FURNACES, KILNS, OVENS OR RETORTS", + "match_score": 0.41 + }, + "F28F": { + "topic_id": "https://openalex.org/T11655", + "topic_display_name": "HIV-related health complications and treatments", + "ipc_label": "DETAILS OF HEAT-EXCHANGE AND HEAT-TRANSFER APPARATUS, OF GENERAL APPLICATION water and air traps, air venting F16", + "match_score": 0.412 + }, + "F41A": { + "topic_id": "https://openalex.org/T13468", + "topic_display_name": "Educational Research and Science Teaching", + "ipc_label": "FUNCTIONAL FEATURES OR DETAILS COMMON TO BOTH SMALLARMS AND ORDNANCE, e.g. CANNONSMOUNTINGS FOR SMALLARMS OR ORDNANCE", + "match_score": 0.367 + }, + "F41G": { + "topic_id": "https://openalex.org/T13049", + "topic_display_name": "Surface Roughness and Optical Measurements", + "ipc_label": "WEAPON SIGHTSAIMING optical aspects thereof G02B", + "match_score": 0.467 + }, + "F99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "G01F": { + "topic_id": "https://openalex.org/T10836", + "topic_display_name": "Metabolomics and Mass Spectrometry Studies", + "ipc_label": "MEASURING VOLUME, VOLUME FLOW, MASS FLOW OR LIQUID LEVELMETERING BY VOLUME", + "match_score": 0.379 + }, + "G01G": { + "topic_id": "https://openalex.org/T13960", + "topic_display_name": "Dietetics, Nutrition, and Education", + "ipc_label": "WEIGHING sorting by weighing B07C5/16", + "match_score": 0.364 + }, + "G01H": { + "topic_id": "https://openalex.org/T10386", + "topic_display_name": "Microstructure and Mechanical Properties of Steels", + "ipc_label": "MEASUREMENT OF MECHANICAL VIBRATIONS OR ULTRASONIC, SONIC OR INFRASONIC WAVES", + "match_score": 0.425 + }, + "G01L": { + "topic_id": "https://openalex.org/T10386", + "topic_display_name": "Microstructure and Mechanical Properties of Steels", + "ipc_label": "MEASURING FORCE, STRESS, TORQUE, WORK, MECHANICAL POWER, MECHANICAL EFFICIENCY, OR FLUID PRESSURE weighing G01G", + "match_score": 0.385 + }, + "G01Q": { + "topic_id": "https://openalex.org/T10801", + "topic_display_name": "Synthetic Aperture Radar (SAR) Applications and Techniques", + "ipc_label": "SCANNING-PROBE TECHNIQUES OR APPARATUSAPPLICATIONS OF SCANNING-PROBE TECHNIQUES, e.g. SCANNING PROBE MICROSCOPY [SPM]", + "match_score": 0.389 + }, + "G01R": { + "topic_id": "https://openalex.org/T10614", + "topic_display_name": "Transcranial Magnetic Stimulation Studies", + "ipc_label": "MEASURING ELECTRIC VARIABLESMEASURING MAGNETIC VARIABLES indicating correct tuning of resonant circuits H03J3/12", + "match_score": 0.379 + }, + "G02B": { + "topic_id": "https://openalex.org/T12391", + "topic_display_name": "Artificial Immune Systems Applications", + "ipc_label": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS", + "match_score": 0.579 + }, + "G04D": { + "topic_id": "https://openalex.org/T13583", + "topic_display_name": "Jury Decision Making Processes", + "ipc_label": "APPARATUS OR TOOLS SPECIALLY DESIGNED FOR MAKING OR MAINTAINING CLOCKS OR WATCHES", + "match_score": 0.378 + }, + "G04F": { + "topic_id": "https://openalex.org/T13293", + "topic_display_name": "Engineering and Test Systems", + "ipc_label": "TIME-INTERVAL MEASURING measuring pulse characteristics G01R, e.g. G01R29/02; in radar or like systems G01S", + "match_score": 0.37 + }, + "G04G": { + "topic_id": "https://openalex.org/T10350", + "topic_display_name": "Electronic Health Records Systems", + "ipc_label": "ELECTRONIC TIME-PIECES", + "match_score": 0.582 + }, + "G04R": { + "topic_id": "https://openalex.org/T12810", + "topic_display_name": "Real-time simulation and control systems", + "ipc_label": "RADIO-CONTROLLED TIME-PIECES", + "match_score": 0.441 + }, + "G05D": { + "topic_id": "https://openalex.org/T10504", + "topic_display_name": "Sensorless Control of Electric Motors", + "ipc_label": "SYSTEMS FOR CONTROLLING OR REGULATING NON-ELECTRIC VARIABLES", + "match_score": 0.536 + }, + "G06C": { + "topic_id": "https://openalex.org/T13155", + "topic_display_name": "Digital Communication and Language", + "ipc_label": "DIGITAL COMPUTERS IN WHICH ALL THE COMPUTATION IS EFFECTED MECHANICALLY score computers for card games A63F1/18", + "match_score": 0.372 + }, + "G06D": { + "topic_id": "https://openalex.org/T12923", + "topic_display_name": "Digital Image Processing Techniques", + "ipc_label": "DIGITAL FLUID-PRESSURE COMPUTING DEVICES", + "match_score": 0.587 + }, + "G06F": { + "topic_id": "https://openalex.org/T13093", + "topic_display_name": "Electric Power Systems and Control", + "ipc_label": "ELECTRIC DIGITAL DATA PROCESSING computer systems based on specific computational models G06N", + "match_score": 0.472 + }, + "G06G": { + "topic_id": "https://openalex.org/T11429", + "topic_display_name": "Semiconductor Lasers and Optical Devices", + "ipc_label": "ANALOGUE COMPUTERS analogue optical computing devices G06E3/00", + "match_score": 0.529 + }, + "G06K": { + "topic_id": "https://openalex.org/T10627", + "topic_display_name": "Advanced Image and Video Retrieval Techniques", + "ipc_label": "GRAPHICAL DATA READING image or video recognition or understanding G06VPRESENTATION OF DATARECORD CARRIERSHANDLING RECORD CARRIERS", + "match_score": 0.354 + }, + "G06N": { + "topic_id": "https://openalex.org/T13806", + "topic_display_name": "Mathematical and Computational Methods", + "ipc_label": "COMPUTING ARRANGEMENTS BASED ON SPECIFIC COMPUTATIONAL MODELS", + "match_score": 0.525 + }, + "G06T": { + "topic_id": "https://openalex.org/T14339", + "topic_display_name": "Image Processing and 3D Reconstruction", + "ipc_label": "IMAGE DATA PROCESSING OR GENERATION, IN GENERAL", + "match_score": 0.541 + }, + "G06V": { + "topic_id": "https://openalex.org/T13579", + "topic_display_name": "Image and Video Stabilization", + "ipc_label": "IMAGE OR VIDEO RECOGNITION OR UNDERSTANDING", + "match_score": 0.75 + }, + "G07G": { + "topic_id": "https://openalex.org/T13321", + "topic_display_name": "Radio, Podcasts, and Digital Media", + "ipc_label": "REGISTERING THE RECEIPT OF CASH, VALUABLES, OR TOKENS digital computing in general G06C, G06F", + "match_score": 0.378 + }, + "G08B": { + "topic_id": "https://openalex.org/T11902", + "topic_display_name": "Intelligent Tutoring Systems and Adaptive Learning", + "ipc_label": "SIGNALLING OR CALLING SYSTEMSORDER TELEGRAPHSALARM SYSTEMS", + "match_score": 0.5 + }, + "G09F": { + "topic_id": "https://openalex.org/T14032", + "topic_display_name": "History and International Relations", + "ipc_label": "DISPLAYINGADVERTISINGSIGNSLABELS OR NAME-PLATESSEALS", + "match_score": 0.391 + }, + "G10L": { + "topic_id": "https://openalex.org/T13244", + "topic_display_name": "Analysis of environmental and stochastic processes", + "ipc_label": "SPEECH ANALYSIS OR SYNTHESISSPEECH RECOGNITIONSPEECH OR VOICE PROCESSINGSPEECH OR AUDIO CODING OR DECODING", + "match_score": 0.359 + }, + "G11C": { + "topic_id": "https://openalex.org/T10472", + "topic_display_name": "Semiconductor materials and devices", + "ipc_label": "STATIC STORES semiconductor memory devices H10B", + "match_score": 0.61 + }, + "G16C": { + "topic_id": "https://openalex.org/T10192", + "topic_display_name": "Catalytic Processes in Materials Science", + "ipc_label": "COMPUTATIONAL CHEMISTRYCHEMOINFORMATICSCOMPUTATIONAL MATERIALS SCIENCE", + "match_score": 0.527 + }, + "G16H": { + "topic_id": "https://openalex.org/T11773", + "topic_display_name": "Healthcare Operations and Scheduling Optimization", + "ipc_label": "HEALTHCARE INFORMATICS, i.e. INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR THE HANDLING OR PROCESSING OF MEDICAL OR HEALTHCARE DATA", + "match_score": 0.384 + }, + "G16Y": { + "topic_id": "https://openalex.org/T13952", + "topic_display_name": "Information Technology and Learning", + "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]", + "match_score": 0.508 + }, + "G16Z": { + "topic_id": "https://openalex.org/T12734", + "topic_display_name": "Information Systems and Technology Applications", + "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS, NOT OTHERWISE PROVIDED FOR", + "match_score": 0.456 + }, + "G21B": { + "topic_id": "https://openalex.org/T10592", + "topic_display_name": "Fusion materials and technologies", + "ipc_label": "FUSION REACTORS uncontrolled reactors G21J", + "match_score": 0.48 + }, + "G21C": { + "topic_id": "https://openalex.org/T10808", + "topic_display_name": "Electric and Hybrid Vehicle Technologies", + "ipc_label": "NUCLEAR REACTORS fusion reactors, hybrid fission-fusion reactors G21B; nuclear explosives G21J", + "match_score": 0.388 + }, + "G21D": { + "topic_id": "https://openalex.org/T12295", + "topic_display_name": "Foucault, Power, and Ethics", + "ipc_label": "NUCLEAR POWER PLANT", + "match_score": 0.565 + }, + "G21J": { + "topic_id": "https://openalex.org/T12405", + "topic_display_name": "Characterization and Applications of Magnetic Nanoparticles", + "ipc_label": "NUCLEAR EXPLOSIVESAPPLICATIONS THEREOF electric or magnetic analogue computers, e.g. simulators, for nuclear physics G06G7/54", + "match_score": 0.413 + }, + "G99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "H01C": { + "topic_id": "https://openalex.org/T12454", + "topic_display_name": "European Political History Analysis", + "ipc_label": "RESISTORS", + "match_score": 0.625 + }, + "H01J": { + "topic_id": "https://openalex.org/T12495", + "topic_display_name": "Electrostatic Discharge in Electronics", + "ipc_label": "ELECTRIC DISCHARGE TUBES OR DISCHARGE LAMPS spark-gaps H01T; arc lamps with consumable electrodes H05B; particle accelerators H05H", + "match_score": 0.381 + }, + "H01M": { + "topic_id": "https://openalex.org/T12495", + "topic_display_name": "Electrostatic Discharge in Electronics", + "ipc_label": "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE DIRECT CONVERSION OF CHEMICAL ENERGY INTO ELECTRICAL ENERGY", + "match_score": 0.383 + }, + "H01P": { + "topic_id": "https://openalex.org/T11429", + "topic_display_name": "Semiconductor Lasers and Optical Devices", + "ipc_label": "WAVEGUIDESRESONATORS, LINES, OR OTHER DEVICES OF THE WAVEGUIDE TYPE operating at optical frequencies G02B", + "match_score": 0.4 + }, + "H01Q": { + "topic_id": "https://openalex.org/T10579", + "topic_display_name": "Cognitive Radio Networks and Spectrum Sensing", + "ipc_label": "ANTENNAS, i.e. RADIO AERIALS radiators or antennas for microwave heating H05B6/72", + "match_score": 0.397 + }, + "H02B": { + "topic_id": "https://openalex.org/T10968", + "topic_display_name": "Statistical Distribution Estimation and Applications", + "ipc_label": "BOARDS, SUBSTATIONS OR SWITCHING ARRANGEMENTS FOR THE SUPPLY OR DISTRIBUTION OF ELECTRIC POWER", + "match_score": 0.411 + }, + "H02G": { + "topic_id": "https://openalex.org/T10607", + "topic_display_name": "Magnetic and transport properties of perovskites and related materials", + "ipc_label": "INSTALLATION OF ELECTRIC CABLES OR LINES, OR OF COMBINED OPTICAL AND ELECTRIC CABLES OR LINES", + "match_score": 0.444 + }, + "H02J": { + "topic_id": "https://openalex.org/T12111", + "topic_display_name": "Industrial Vision Systems and Defect Detection", + "ipc_label": "CIRCUIT ARRANGEMENTS OR SYSTEMS FOR SUPPLYING OR DISTRIBUTING ELECTRIC POWERSYSTEMS FOR STORING ELECTRIC ENERGY", + "match_score": 0.369 + }, + "H02N": { + "topic_id": "https://openalex.org/T10768", + "topic_display_name": "Electric Vehicles and Infrastructure", + "ipc_label": "ELECTRIC MACHINES NOT OTHERWISE PROVIDED FOR", + "match_score": 0.475 + }, + "H03C": { + "topic_id": "https://openalex.org/T10030", + "topic_display_name": "Electrocatalysts for Energy Conversion", + "ipc_label": "MODULATION masers or lasers H01S; coding, decoding or code conversion H03M", + "match_score": 0.429 + }, + "H03G": { + "topic_id": "https://openalex.org/T13924", + "topic_display_name": "Internet of Things and Social Network Interactions", + "ipc_label": "CONTROL OF AMPLIFICATION impedance networks, e.g. attenuators, H03H; control of transmission in lines H04B3/04", + "match_score": 0.375 + }, + "H03J": { + "topic_id": "https://openalex.org/T14117", + "topic_display_name": "Integrated Circuits and Semiconductor Failure Analysis", + "ipc_label": "TUNING RESONANT CIRCUITSSELECTING RESONANT CIRCUITS", + "match_score": 0.476 + }, + "H03L": { + "topic_id": "https://openalex.org/T13257", + "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", + "ipc_label": "AUTOMATIC CONTROL, STARTING, SYNCHRONISATION, OR STABILISATION OF GENERATORS OF ELECTRONIC OSCILLATIONS OR PULSES of dynamo-electric generators H02P", + "match_score": 0.355 + }, + "H04B": { + "topic_id": "https://openalex.org/T12804", + "topic_display_name": "Thermal Analysis in Power Transmission", + "ipc_label": "TRANSMISSION", + "match_score": 1.0 + }, + "H04H": { + "topic_id": "https://openalex.org/T12593", + "topic_display_name": "Communication in Education and Healthcare", + "ipc_label": "BROADCAST COMMUNICATION multiplex communication H04J; pictorial communication aspects of broadcast systems H04N", + "match_score": 0.408 + }, + "H04K": { + "topic_id": "https://openalex.org/T13317", + "topic_display_name": "Media, Communication, and Education", + "ipc_label": "SECRET COMMUNICATIONJAMMING OF COMMUNICATION", + "match_score": 0.633 + }, + "H04L": { + "topic_id": "https://openalex.org/T12607", + "topic_display_name": "Personal Information Management and User Behavior", + "ipc_label": "TRANSMISSION OF DIGITAL INFORMATION, e.g. TELEGRAPHIC COMMUNICATION arrangements common to telegraphic and telephonic communication H04M", + "match_score": 0.422 + }, + "H04M": { + "topic_id": "https://openalex.org/T13905", + "topic_display_name": "Telecommunications and Broadcasting Technologies", + "ipc_label": "TELEPHONIC COMMUNICATION circuits for controlling other apparatus via a telephone cable and not involving telephone switching apparatus G08", + "match_score": 0.374 + }, + "H04N": { + "topic_id": "https://openalex.org/T13317", + "topic_display_name": "Media, Communication, and Education", + "ipc_label": "PICTORIAL COMMUNICATION, e.g. TELEVISION", + "match_score": 0.613 + }, + "H04Q": { + "topic_id": "https://openalex.org/T10575", + "topic_display_name": "Wireless Communication Networks Research", + "ipc_label": "SELECTING switches, relays, selectors H01H; wireless communication networks H04W", + "match_score": 0.55 + }, + "H04S": { + "topic_id": "https://openalex.org/T11575", + "topic_display_name": "Nonlinear Photonic Systems", + "ipc_label": "STEREOPHONIC SYSTEMS", + "match_score": 0.696 + }, + "H04T": { + "topic_id": "https://openalex.org/T11121", + "topic_display_name": "Public Relations and Crisis Communication", + "ipc_label": "INDEXING SCHEME RELATING TO STANDARDS FOR ELECTRIC COMMUNICATION TECHNIQUE CLASS H04", + "match_score": 0.512 + }, + "H04W": { + "topic_id": "https://openalex.org/T10575", + "topic_display_name": "Wireless Communication Networks Research", + "ipc_label": "WIRELESS COMMUNICATION NETWORKS broadcast communication H04H; communication systems using wireless links for non-selective communication, e.g. wireless extensions H04M1/72", + "match_score": 0.36 + }, + "H05B": { + "topic_id": "https://openalex.org/T13093", + "topic_display_name": "Electric Power Systems and Control", + "ipc_label": "ELECTRIC HEATINGELECTRIC LIGHT SOURCES NOT OTHERWISE PROVIDED FORCIRCUIT ARRANGEMENTS FOR ELECTRIC LIGHT SOURCES, IN GENERAL", + "match_score": 0.36 + }, + "H10B": { + "topic_id": "https://openalex.org/T10299", + "topic_display_name": "Photonic and Optical Devices", + "ipc_label": "ELECTRONIC MEMORY DEVICES", + "match_score": 0.667 + }, + "H10K": { + "topic_id": "https://openalex.org/T10045", + "topic_display_name": "Organic Electronics and Photovoltaics", + "ipc_label": "ORGANIC ELECTRIC SOLID-STATE DEVICES", + "match_score": 0.658 + }, + "H10N": { + "topic_id": "https://openalex.org/T10768", + "topic_display_name": "Electric Vehicles and Infrastructure", + "ipc_label": "ELECTRIC SOLID-STATE DEVICES NOT OTHERWISE PROVIDED FOR", + "match_score": 0.44 + }, + "H99Z": { + "topic_id": "https://openalex.org/T12682", + "topic_display_name": "Smart Materials for Construction", + "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", + "match_score": 0.494 + }, + "Y02A": { + "topic_id": "https://openalex.org/T10895", + "topic_display_name": "Species Distribution and Climate Change", + "ipc_label": "TECHNOLOGIES FOR ADAPTATION TO CLIMATE CHANGE", + "match_score": 0.643 + }, + "Y02B": { + "topic_id": "https://openalex.org/T13734", + "topic_display_name": "Advanced Computational Techniques and Applications", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO BUILDINGS, e.g. HOUSING, HOUSE APPLIANCES OR RELATED END-USER APPLICATIONS", + "match_score": 0.425 + }, + "Y02C": { + "topic_id": "https://openalex.org/T10945", + "topic_display_name": "Lysosomal Storage Disorders Research", + "ipc_label": "CAPTURE, STORAGE, SEQUESTRATION OR DISPOSAL OF GREENHOUSE GASES [GHG]", + "match_score": 0.419 + }, + "Y02P": { + "topic_id": "https://openalex.org/T11488", + "topic_display_name": "Climate Change Communication and Perception", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES IN THE PRODUCTION OR PROCESSING OF GOODS", + "match_score": 0.525 + }, + "Y02T": { + "topic_id": "https://openalex.org/T11488", + "topic_display_name": "Climate Change Communication and Perception", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO TRANSPORTATION", + "match_score": 0.598 + }, + "Y02W": { + "topic_id": "https://openalex.org/T11404", + "topic_display_name": "Irrigation Practices and Water Management", + "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO WASTEWATER TREATMENT OR WASTE MANAGEMENT", + "match_score": 0.504 + }, + "Y10S": { + "topic_id": "https://openalex.org/T13332", + "topic_display_name": "Historical Studies on Reproduction, Gender, Health, and Societal Changes", + "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER USPC CROSS-REFERENCE ART COLLECTIONS [XRACs] AND DIGESTS", + "match_score": 0.412 + }, + "Y10T": { + "topic_id": "https://openalex.org/T10885", + "topic_display_name": "Gene expression and cancer classification", + "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER US CLASSIFICATION", + "match_score": 0.484 + } + }, + "group": {}, + "subgroup": {} +} \ No newline at end of file diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py index 1de0f927..320ce506 100644 --- a/service/src/main/inse/patents/authors/identity.py +++ b/service/src/main/inse/patents/authors/identity.py @@ -1,8 +1,7 @@ """Identity signals used to decide whether a patent really belongs to a person. These are the *strong* signals (name specificity, institution/assignee overlap) -that distinguish one same-named person from another. Topic/IPC similarity is only -a supporting plausibility signal and lives in ``ipc_topic_matching``. +that distinguish one same-named person from another. """ from __future__ import annotations diff --git a/service/src/main/inse/patents/authors/ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py new file mode 100644 index 00000000..957caa8e --- /dev/null +++ b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py @@ -0,0 +1,405 @@ +"""Precomputed IPC/CPC symbol → OpenAlex topic lookups (1:1 per hierarchy level).""" +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from functools import lru_cache +from typing import Any + +from inse.models.openalex.author import Author +from inse.patents.common import model +from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol + +MAPPING_FILENAME = "ipc_openalex_topic_mapping.json" +TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json" +LEVELS = ("section", "class", "subclass", "group", "subgroup") +MATCH_LEVELS = ("subgroup", "group", "subclass") + +# High-frequency IPC subclasses missing from the ES-built mapping file. +SUBCLASS_TOPIC_OVERRIDES: dict[str, str] = { + "A61B": "Cardiac electrophysiology and arrhythmias", + "A61K": "Pharmaceutical studies and practices", + "A61P": "Cancer Immunotherapy and Biomarkers", + "C07K": "Cancer Immunotherapy and Biomarkers", + "C12N": "Biotechnology and Related Fields", + "C12Q": "Cancer Immunotherapy and Biomarkers", + "G01N": "Analytical Methods in Pharmaceuticals", +} + + +@dataclass(frozen=True) +class MappedOpenAlexTopic: + topic_id: str + topic_display_name: str | None = None + subfield_id: str | None = None + field_id: str | None = None + domain_id: str | None = None + subfield_name: str | None = None + field_name: str | None = None + domain_name: str | None = None + ipc_level: str | None = None + ipc_symbol: str | None = None + + +@dataclass(frozen=True) +class OpenAlexTopicRefs: + topic_ids: frozenset[str] + subfield_ids: frozenset[str] + field_ids: frozenset[str] + domain_ids: frozenset[str] + + +def normalize_openalex_id(value: str | None) -> str | None: + if not value or not str(value).strip(): + return None + cleaned = str(value).strip() + if cleaned.startswith("https://openalex.org/"): + return cleaned.rsplit("/", 1)[-1] + return cleaned + + +def _data_dir() -> str: + for base in ( + "/data", + os.path.normpath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data") + ), + ): + if os.path.isdir(base): + return base + return os.path.normpath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data") + ) + + +def _mapping_path() -> str: + return os.path.join(_data_dir(), MAPPING_FILENAME) + + +@lru_cache(maxsize=1) +def _load_topic_cache() -> dict[str, dict[str, str]]: + path = os.path.join(_data_dir(), TOPIC_CACHE_FILENAME) + try: + with open(path, encoding="utf-8") as handle: + raw = json.load(handle) + except (OSError, json.JSONDecodeError): + return {} + if not isinstance(raw, dict): + return {} + return { + display_name: { + "topic_id": str(info.get("topic_id", "")), + "subfield": info.get("subfield"), + "field": info.get("field"), + "domain": info.get("domain"), + } + for display_name, info in raw.items() + if isinstance(info, dict) and info.get("topic_id") + } + + +def _enrich_mapped_topic(mapped: MappedOpenAlexTopic) -> MappedOpenAlexTopic: + cache = _load_topic_cache() + topic_name = mapped.topic_display_name or "" + info = cache.get(topic_name) + if info is None: + for candidate in cache.values(): + if candidate.get("topic_id") == mapped.topic_id: + info = candidate + break + if info is None: + return mapped + return MappedOpenAlexTopic( + topic_id=mapped.topic_id, + topic_display_name=mapped.topic_display_name or topic_name, + subfield_id=mapped.subfield_id, + field_id=mapped.field_id, + domain_id=mapped.domain_id, + subfield_name=info.get("subfield"), + field_name=info.get("field"), + domain_name=info.get("domain"), + ipc_level=mapped.ipc_level, + ipc_symbol=mapped.ipc_symbol, + ) + + +def _mapped_from_topic_name( + topic_display_name: str, + *, + ipc_level: str, + ipc_symbol: str, +) -> MappedOpenAlexTopic | None: + cache = _load_topic_cache() + info = cache.get(topic_display_name) + if info is None: + return None + return _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=info["topic_id"], + topic_display_name=topic_display_name, + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + ) + ) + + +def _apply_subclass_overrides( + parsed: dict[str, dict[str, MappedOpenAlexTopic]], +) -> None: + for symbol, topic_name in SUBCLASS_TOPIC_OVERRIDES.items(): + mapped = _mapped_from_topic_name( + topic_name, + ipc_level="subclass", + ipc_symbol=_normalize_symbol(symbol), + ) + if mapped is not None: + parsed["subclass"][_normalize_symbol(symbol)] = mapped + + +@lru_cache(maxsize=1) +def load_ipc_openalex_mapping() -> dict[str, dict[str, MappedOpenAlexTopic]]: + path = _mapping_path() + try: + with open(path, encoding="utf-8") as handle: + raw = json.load(handle) + except (OSError, json.JSONDecodeError): + raw = {} + + parsed: dict[str, dict[str, MappedOpenAlexTopic]] = {level: {} for level in LEVELS} + for level in LEVELS: + for symbol, entry in (raw.get(level) or {}).items(): + if not isinstance(entry, dict): + continue + topic_id = entry.get("topic_id") + if not topic_id: + continue + normalized_symbol = _normalize_symbol(symbol) + mapped = _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=entry.get("topic_display_name"), + subfield_id=entry.get("subfield_id"), + field_id=entry.get("field_id"), + domain_id=entry.get("domain_id"), + subfield_name=entry.get("subfield"), + field_name=entry.get("field"), + domain_name=entry.get("domain"), + ipc_level=level, + ipc_symbol=normalized_symbol, + ) + ) + parsed[level][normalized_symbol] = mapped + _apply_subclass_overrides(parsed) + return parsed + + +def clear_mapping_cache() -> None: + load_ipc_openalex_mapping.cache_clear() + _load_topic_cache.cache_clear() + + +def _normalize_symbol(symbol: str | None) -> str: + if not symbol: + return "" + return symbol.strip().upper().replace(" ", "") + + +def _entry_from_raw(entry: dict[str, Any]) -> MappedOpenAlexTopic | None: + topic_id = entry.get("topic_id") + if not topic_id: + return None + return MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=entry.get("topic_display_name"), + subfield_id=entry.get("subfield_id"), + field_id=entry.get("field_id"), + domain_id=entry.get("domain_id"), + ipc_level=entry.get("ipc_level"), + ipc_symbol=entry.get("ipc_symbol"), + ) + + +def lookup_mapped_topic( + mapping: dict[str, dict[str, MappedOpenAlexTopic]], + level: str, + symbol: str | None, +) -> MappedOpenAlexTopic | None: + if not symbol: + return None + return mapping.get(level, {}).get(_normalize_symbol(symbol)) + + +def hierarchy_keys_for_symbol(raw_code: str): + return parse_ipc_symbol(extract_ipc_symbol(raw_code)) + + +def resolve_mapped_topics_for_code( + raw_code: str, + mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, +) -> list[MappedOpenAlexTopic]: + table = mapping if mapping is not None else load_ipc_openalex_mapping() + keys = hierarchy_keys_for_symbol(raw_code) + if keys is None: + return [] + + candidates: list[tuple[str, str | None]] = [ + ("subgroup", keys.subgroup or keys.normalized), + ("group", keys.main_group or keys.normalized), + ("subclass", keys.subclass), + ] + for level, symbol in candidates: + if not symbol: + continue + mapped = lookup_mapped_topic(table, level, symbol) + if mapped is not None: + return [mapped] + return [] + + +def resolve_mapped_topics_for_patent( + 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() + seen: set[str] = set() + resolved: list[MappedOpenAlexTopic] = [] + for raw_code in (*patent.ipc, *patent.cpc): + for mapped in resolve_mapped_topics_for_code(raw_code, table): + topic_key = normalize_openalex_id(mapped.topic_id) or mapped.topic_id + if topic_key in seen: + continue + seen.add(topic_key) + resolved.append(mapped) + return resolved + + +def author_openalex_topic_refs(author: Author) -> OpenAlexTopicRefs: + topic_ids: set[str] = set() + subfield_ids: set[str] = set() + field_ids: set[str] = set() + domain_ids: set[str] = set() + + for topic in author.topics or []: + topic_id = normalize_openalex_id(getattr(topic, "id", None)) + if topic_id: + topic_ids.add(topic_id) + subfield = getattr(topic, "subfield", None) + if subfield is not None: + subfield_id = normalize_openalex_id(getattr(subfield, "id", None)) + if subfield_id: + subfield_ids.add(subfield_id) + field = getattr(topic, "var_field", None) or getattr(topic, "field", None) + if field is not None: + field_id = normalize_openalex_id(getattr(field, "id", None)) + if field_id: + field_ids.add(field_id) + domain = getattr(topic, "domain", None) + if domain is not None: + domain_id = normalize_openalex_id(getattr(domain, "id", None)) + if domain_id: + domain_ids.add(domain_id) + + return OpenAlexTopicRefs( + topic_ids=frozenset(topic_ids), + subfield_ids=frozenset(subfield_ids), + field_ids=frozenset(field_ids), + domain_ids=frozenset(domain_ids), + ) + + +def author_topic_labels(author: Author) -> set[str]: + labels: set[str] = set() + for topic in author.topics or []: + if topic.display_name: + labels.add(topic.display_name.casefold()) + subfield = getattr(topic, "subfield", None) + if subfield is not None and getattr(subfield, "display_name", None): + labels.add(subfield.display_name.casefold()) + field = getattr(topic, "var_field", None) or getattr(topic, "field", None) + if field is not None and getattr(field, "display_name", None): + labels.add(field.display_name.casefold()) + return labels + + +def _topic_labels_match(mapped: MappedOpenAlexTopic, author: Author) -> bool: + mapped_label = (mapped.topic_display_name or "").casefold() + if not mapped_label: + return False + + author_labels = author_topic_labels(author) + if mapped_label in author_labels: + return True + + 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: + return True + label_tokens = {token for token in label.split() if len(token) > 2} + if len(mapped_tokens & label_tokens) >= 2: + return True + return False + + +def mapped_topic_refs(mapped: MappedOpenAlexTopic) -> OpenAlexTopicRefs: + topic_id = normalize_openalex_id(mapped.topic_id) + return OpenAlexTopicRefs( + topic_ids=frozenset({topic_id}) if topic_id else frozenset(), + subfield_ids=frozenset( + {normalize_openalex_id(mapped.subfield_id)} + if normalize_openalex_id(mapped.subfield_id) + else set() + ), + field_ids=frozenset( + {normalize_openalex_id(mapped.field_id)} + if normalize_openalex_id(mapped.field_id) + else set() + ), + domain_ids=frozenset( + {normalize_openalex_id(mapped.domain_id)} + if normalize_openalex_id(mapped.domain_id) + else set() + ), + ) + + +def _hierarchy_names_overlap(mapped: MappedOpenAlexTopic, author: Author) -> bool: + mapped_names = { + name.casefold() + for name in (mapped.subfield_name, mapped.field_name, mapped.domain_name) + if name + } + if not mapped_names: + return False + return bool(mapped_names & author_topic_labels(author)) + + +def refs_overlap(left: OpenAlexTopicRefs, right: OpenAlexTopicRefs) -> bool: + if left.topic_ids & right.topic_ids: + return True + if left.subfield_ids & right.subfield_ids: + return True + if left.field_ids & right.field_ids: + return True + return False + + +def patent_topics_match_author( + patent: model.PatentEntry, + author: Author, + mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None, +) -> 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 + ) diff --git a/service/src/main/inse/patents/authors/ipc_topic_matching.py b/service/src/main/inse/patents/authors/ipc_topic_matching.py deleted file mode 100644 index 2296ce03..00000000 --- a/service/src/main/inse/patents/authors/ipc_topic_matching.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Semantic comparison of patent text and classifications with author OpenAlex topics.""" -from __future__ import annotations - -from dataclasses import dataclass -from typing import Literal - -import numpy as np - -from inse.patents.common import model -from inse.util import get_model - -STRONG_SIMILARITY_THRESHOLD = 0.82 -WEAK_SIMILARITY_THRESHOLD = 0.78 -CONFLICT_SIMILARITY_THRESHOLD = 0.78 - -TopicMatchLevel = Literal["strong", "weak", "none"] - - -@dataclass(frozen=True) -class TopicMatchResult: - level: TopicMatchLevel - similarity: float - topic_conflict: bool - - -def author_topic_names(author) -> list[str]: - topics: list[tuple[str, float]] = [] - for topic in author.topics or []: - if not topic.display_name: - continue - topics.append((topic.display_name, float(topic.score or 0.0))) - topics.sort(key=lambda item: item[1], reverse=True) - return [name for name, _score in topics[:15]] - - -def _label_from_classification_field(field: str) -> str: - cleaned = field.strip() - if " - " in cleaned: - return cleaned.split(" - ", 1)[1].strip() - return cleaned - - -def classification_description_labels(patent: model.PatentEntry) -> list[str]: - labels: list[str] = [] - seen: set[str] = set() - - for classification in (*patent.ipc_descriptions, *patent.cpc_descriptions): - for field in ( - classification.section, - classification.ipc_class, - classification.subclass, - classification.main_group, - classification.subgroup, - ): - if not field: - continue - label = _label_from_classification_field(field) - key = label.casefold() - if not label or key in seen: - continue - seen.add(key) - labels.append(label) - - return labels - - -def patent_topic_text(patent: model.PatentEntry) -> str: - parts: list[str] = [] - - if patent.title and patent.title.strip(): - parts.append(patent.title.strip()) - - if patent.abstract and patent.abstract.strip(): - parts.append(patent.abstract.strip()) - - classification_labels = classification_description_labels(patent) - if classification_labels: - parts.append(f"IPC/CPC: {', '.join(classification_labels)}") - - return " ".join(parts) - - -def patent_has_topic_signal(patent: model.PatentEntry) -> bool: - return bool(patent_topic_text(patent).strip()) - - -def _encode_texts(texts: list[str]) -> np.ndarray: - if not texts: - return np.empty((0, 0)) - model_instance = get_model() - return model_instance.encode(texts, normalize_embeddings=True) - - -def _max_cosine_similarity(left: np.ndarray, right: np.ndarray) -> float: - if left.size == 0 or right.size == 0: - return 0.0 - if left.ndim == 1: - left = left.reshape(1, -1) - if right.ndim == 1: - right = right.reshape(1, -1) - return float(np.max(left @ right.T)) - - -def _match_level(similarity: float) -> TopicMatchLevel: - if similarity >= STRONG_SIMILARITY_THRESHOLD: - return "strong" - if similarity >= WEAK_SIMILARITY_THRESHOLD: - return "weak" - return "none" - - -def match_patent_to_topics( - patent: model.PatentEntry, - topic_names: list[str], - *, - patent_vector: np.ndarray | None = None, - topic_vectors: np.ndarray | None = None, -) -> TopicMatchResult: - if not topic_names: - return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - - patent_text = patent_topic_text(patent) - if not patent_text: - return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - - patent_embedding = patent_vector - if patent_embedding is None: - patent_embedding = _encode_texts([patent_text])[0] - - topic_embedding = topic_vectors - if topic_embedding is None: - topic_embedding = _encode_texts(topic_names) - - similarity = _max_cosine_similarity(patent_embedding, topic_embedding) - topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD - - return TopicMatchResult( - level=_match_level(similarity), - similarity=round(similarity, 3), - topic_conflict=topic_conflict, - ) - - -def match_patents_to_topics( - patents: list[model.PatentEntry], - topic_names: list[str], -) -> list[TopicMatchResult]: - if not patents: - return [] - if not topic_names: - return [ - TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - for _patent in patents - ] - - patent_texts = [patent_topic_text(patent) for patent in patents] - texts_to_encode = [text for text in patent_texts if text] - if not texts_to_encode: - return [ - TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - for _patent in patents - ] - - encoded = _encode_texts(texts_to_encode) - topic_vectors = _encode_texts(topic_names) - - encoded_by_text = { - text: encoded[index] - for index, text in enumerate(texts_to_encode) - } - - results: list[TopicMatchResult] = [] - for patent_text in patent_texts: - if not patent_text: - results.append( - TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - ) - continue - similarity = _max_cosine_similarity( - encoded_by_text[patent_text], - topic_vectors, - ) - topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD - results.append( - TopicMatchResult( - level=_match_level(similarity), - similarity=round(similarity, 3), - topic_conflict=topic_conflict, - ) - ) - return results diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 00753674..e9109625 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -9,10 +9,8 @@ from starlette.status import HTTP_503_SERVICE_UNAVAILABLE 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.topic_filter import ( - filter_patents_by_author_topics, - to_author_patent_entry, -) +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.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( @@ -28,7 +26,6 @@ from inse.models.openalex.author import Author logger = logging.getLogger(__name__) - async def get_patents_by_author_id( author_id: str, client: PatentSearchClient | None = None, @@ -71,9 +68,9 @@ async def get_patents_by_author_id( all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) all_patents = deduplicate_patents(all_patents) patent_hit_count = len(all_patents) - name_matched = filter_patents_by_author_name(all_patents, author_name) + matched_patents = filter_patents_by_author_name(all_patents, author_name) - if not name_matched: + if not matched_patents: return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, @@ -81,54 +78,43 @@ async def get_patents_by_author_id( patents=[], ) - await enrich_patents_classifications(name_matched, ipc_search_client) + await enrich_patents_classifications(matched_patents, ipc_search_client) - # Ambiguity is derived only from existing project data: how many patents the - # name search returned and how many same-named authors exist in the local - # OpenAlex index. full_name_count = await person_logic.count_authors_by_display_name(author_name) + parsed_for_last = parse_person_name(author_name) + last_name_count: int | None = None + if parsed_for_last and not parsed_for_last.is_single_token: + last_name_count = await person_logic.count_authors_by_last_name( + parsed_for_last.last_name + ) is_ambiguous = is_ambiguous_name( author_name, patent_hit_count=patent_hit_count, openalex_full_name_count=full_name_count, + openalex_last_name_count=last_name_count, ) - # Only pay for the extra works aggregation when the author document has no - # topics of its own. - fallback_topics: list[str] = [] - if not (author.topics or []): - fallback_topics = await person_logic.get_topic_names_for_author(author_id) - - logger.info( - "Topic filtering for %s: ambiguous=%s (patent_hits=%d, openalex_same_name=%d), " - "%d author topics, %d fallback topics, %d name-matched patents", - author_name, - is_ambiguous, - patent_hit_count, - full_name_count, - len(author.topics or []), - len(fallback_topics), - len(name_matched), - ) - - # The sentence-transformer encoding is CPU-bound; run it off the event loop - # so it does not block other requests. - filtered_patents = await asyncio.to_thread( - filter_patents_by_author_topics, - name_matched, + filtered = filter_patents_by_ipc_topic_mapping( + matched_patents, author, is_ambiguous=is_ambiguous, - fallback_topic_names=fallback_topics, + ) + + logger.info( + "IPC topic mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter", + author_name, + is_ambiguous, + len(matched_patents), + len(filtered), ) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, - patent_count=len(filtered_patents), - patents=[to_author_patent_entry(item) for item in filtered_patents], + patent_count=len(filtered), + patents=[item.patent for item in filtered], ) - async def _search_both_indices(client, display_name: str): return await asyncio.gather( client.search_epo(client.epo_query_by_inventor(display_name)), diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index 384678e9..f55ff54f 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -142,7 +142,9 @@ def name_matches_person(inventor_name: str, person_display_name: str) -> bool: if not _family_name_matches(author, inventor): return False - return _given_name_matches(author, inventor) + if not _given_name_matches(author, inventor): + return False + return _author_middle_initials_corroborated(author, inventor) def first_name_match_kind_for_person( @@ -337,4 +339,27 @@ def _given_names_full_match( ): return False + return _author_middle_initials_corroborated(author, inventor) + + +def _author_middle_initials_corroborated( + author: ParsedPersonName, + inventor: ParsedPersonName, +) -> bool: + """Require middle initials in the author name to appear on the inventor side. + + Prevents false positives such as attributing patents for "Schmitz, Oliver" + to the distinct person "Oliver J. Schmitz". + """ + if len(author.given_names) <= 1: + return True + + for author_given in author.given_names[1:]: + if _initial_letter(author_given) is None: + continue + if not any( + tokens_equal(author_given, inventor_given, allow_initial=True) + for inventor_given in inventor.given_names + ): + return False return True 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 new file mode 100644 index 00000000..9865ae6c --- /dev/null +++ b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py @@ -0,0 +1,155 @@ +from inse.models.openalex.author import Author +from inse.models.openalex.work_topic import WorkTopic +from inse.models.openalex.work_topic_domain import WorkTopicDomain +from inse.models.openalex.work_topic_field import WorkTopicField +from inse.models.openalex.work_topic_subfield import WorkTopicSubfield +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, + patent_topics_match_author, + resolve_mapped_topics_for_code, +) +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.common import model + + +def _author_with_topic( + topic_id: str, + display_name: str, + *, + subfield_id: str = "https://openalex.org/subfields/2208", + field_id: str = "https://openalex.org/fields/22", + domain_id: str = "https://openalex.org/domains/3", +) -> Author: + return Author( + display_name="Test Author", + topics=[ + WorkTopic( + id=topic_id, + display_name=display_name, + score=1.0, + subfield=WorkTopicSubfield( + id=subfield_id, + display_name="Subfield", + ), + var_field=WorkTopicField( + id=field_id, + display_name="Field", + ), + domain=WorkTopicDomain( + id=domain_id, + display_name="Domain", + ), + ) + ], + ) + + +def _patent(ipc_codes: list[str]) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP1", + source="EPO", + ipc=ipc_codes, + ) + + +def _custom_mapping() -> dict[str, dict[str, mapping_module.MappedOpenAlexTopic]]: + table: dict[str, dict[str, mapping_module.MappedOpenAlexTopic]] = { + level: {} for level in ("section", "class", "subclass", "group", "subgroup") + } + table["subclass"]["H01L"] = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + topic_display_name="Semiconductor materials and devices", + ipc_level="subclass", + ipc_symbol="H01L", + ) + table["subclass"]["A61B"] = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T10217", + topic_display_name="Cardiac electrophysiology and arrhythmias", + ipc_level="subclass", + ipc_symbol="A61B", + ) + return table + + +def test_resolve_mapped_topics_uses_subclass_mapping() -> None: + custom = _custom_mapping() + mapped = resolve_mapped_topics_for_code("H01L 21/02", custom) + assert mapped + assert mapped[0].topic_id.endswith("T99999") + + +def test_patent_topics_match_author_on_topic_id() -> None: + custom = _custom_mapping() + author = _author_with_topic( + "https://openalex.org/T99999", + "Semiconductor materials and devices", + ) + patent = _patent(["H01L 21/02"]) + assert patent_topics_match_author(patent, author, custom) is True + + +def test_patent_topics_do_not_match_unrelated_author() -> None: + custom = _custom_mapping() + author = _author_with_topic( + "https://openalex.org/T10217", + "Cardiac electrophysiology and arrhythmias", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + patent = _patent(["H01L 21/02"]) + assert patent_topics_match_author(patent, author, custom) is False + + +def test_filter_rejects_ambiguous_name_without_topic_match() -> None: + custom = _custom_mapping() + author = _author_with_topic( + "https://openalex.org/T10217", + "Cardiac electrophysiology and arrhythmias", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + patents = [ + _patent(["H01L 21/02"]), + _patent(["A61B 5/00"]), + ] + filtered = filter_patents_by_ipc_topic_mapping( + patents, + author, + is_ambiguous=True, + mapping=custom, + ) + assert len(filtered) == 1 + assert filtered[0].patent.ipc == ["A61B 5/00"] + + +def test_filter_rejects_rare_name_on_topic_conflict() -> None: + custom = _custom_mapping() + author = _author_with_topic( + "https://openalex.org/T10217", + "Cardiac electrophysiology and arrhythmias", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", + domain_id="https://openalex.org/domains/4", + ) + patents = [_patent(["H01L 21/02"])] + filtered = filter_patents_by_ipc_topic_mapping( + patents, + author, + is_ambiguous=False, + mapping=custom, + ) + assert filtered == [] + + +def test_custom_mapping_table() -> None: + custom = _custom_mapping() + author = Author( + display_name="Custom", + topics=[WorkTopic(id="https://openalex.org/T99999", display_name="Semiconductor materials and devices")], + ) + patent = _patent(["H01L 21/02"]) + assert patent_topics_match_author(patent, author, custom) is True diff --git a/service/src/main/inse/patents/authors/test_ipc_topic_matching.py b/service/src/main/inse/patents/authors/test_ipc_topic_matching.py deleted file mode 100644 index 60599cc5..00000000 --- a/service/src/main/inse/patents/authors/test_ipc_topic_matching.py +++ /dev/null @@ -1,145 +0,0 @@ -import numpy as np -import pytest - -from inse.patents.authors import ipc_topic_matching -from inse.patents.authors.ipc_topic_matching import ( - CONFLICT_SIMILARITY_THRESHOLD, - STRONG_SIMILARITY_THRESHOLD, - WEAK_SIMILARITY_THRESHOLD, - classification_description_labels, - match_patents_to_topics, - patent_topic_text, -) -from inse.patents.common import model - - -def _cluster_vector(label: str) -> np.ndarray: - vectors = { - "medical": np.array([1.0, 0.0, 0.0]), - "automotive": np.array([0.0, 1.0, 0.0]), - "wireless": np.array([0.95, 0.05, 0.0]), - } - vector = vectors[label] - return vector / np.linalg.norm(vector) - - -def _label_text(text: str) -> str: - lowered = text.lower() - if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire", "rubber tread")): - return "automotive" - if any(word in lowered for word in ("medical", "cardiac", "heart", "atherosclerosis")): - return "medical" - if any(word in lowered for word in ("wireless", "sensor", "network")): - return "wireless" - return "medical" - - -@pytest.fixture(autouse=True) -def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: - def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: - return np.stack([_cluster_vector(_label_text(text)) for text in texts]) - - monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) - - -def _classification(**fields: str) -> model.IpcClassification: - return model.IpcClassification(symbol="A61B 5/00", **fields) - - -def _patent(**kwargs) -> model.PatentEntry: - return model.PatentEntry( - patent_id="EP1", - source="EPO", - **kwargs, - ) - - -def test_patent_topic_text_includes_title_abstract_and_classifications() -> None: - patent = _patent( - title="Vehicle pneumatic tyre and rubber mixture for a tread", - abstract="Pneumatic vehicle tire in radial design with profiled tread.", - ipc_descriptions=[ - _classification( - section="B - Performing operations; transporting", - ipc_class="B60 - Vehicles in general", - main_group="B60C - Tyres; tyre inflation", - ) - ], - ) - text = patent_topic_text(patent) - assert "Vehicle pneumatic tyre" in text - assert "Pneumatic vehicle tire" in text - assert "IPC/CPC:" in text - assert "Tyres" in text - assert "Vehicles in general" in text - - -def test_classification_description_labels_extracts_readable_names() -> None: - patent = _patent( - ipc_descriptions=[ - _classification( - section="A - Human necessities", - ipc_class="A61 - Medical science", - main_group="A61B 5/00 - Measuring for diagnostic purposes", - ) - ] - ) - labels = classification_description_labels(patent) - assert "Human necessities" in labels - assert "Medical science" in labels - assert "Measuring for diagnostic purposes" in labels - - -def test_match_patents_to_topics_strong_for_related_domain() -> None: - patent = _patent( - title="Cardiac arrhythmia monitoring system", - abstract="Heart rhythm monitoring for coronary artery disease.", - ipc_descriptions=[ - _classification( - section="A - Human necessities", - ipc_class="A61 - Medical or veterinary science", - ) - ], - ) - results = match_patents_to_topics( - [patent], - ["Cardiac arrhythmia and coronary artery disease"], - ) - assert results[0].level == "strong" - assert results[0].similarity >= STRONG_SIMILARITY_THRESHOLD - assert not results[0].topic_conflict - - -def test_match_patents_to_topics_conflict_for_unrelated_domain() -> None: - patent = _patent( - title="Vehicle pneumatic tyre and rubber mixture for a tread", - abstract="Automotive tire tread composition for pneumatic tyres.", - ipc_descriptions=[ - _classification( - section="B - Performing operations", - ipc_class="B60 - Vehicles", - main_group="B60C - Tyres", - ) - ], - ) - results = match_patents_to_topics( - [patent], - ["Cardiac arrhythmia and coronary artery disease"], - ) - assert results[0].topic_conflict - assert results[0].similarity < CONFLICT_SIMILARITY_THRESHOLD - - -def test_match_patents_without_author_topics_is_neutral() -> None: - patent = _patent( - title="Vehicle pneumatic tyre", - ipc_descriptions=[_classification(section="B60 - Vehicles")], - ) - results = match_patents_to_topics([patent], []) - assert results[0].level == "none" - assert not results[0].topic_conflict - - -def test_threshold_ordering() -> None: - assert CONFLICT_SIMILARITY_THRESHOLD <= WEAK_SIMILARITY_THRESHOLD - assert WEAK_SIMILARITY_THRESHOLD < STRONG_SIMILARITY_THRESHOLD diff --git a/service/src/main/inse/patents/authors/test_topic_filter.py b/service/src/main/inse/patents/authors/test_topic_filter.py deleted file mode 100644 index bf8d79c0..00000000 --- a/service/src/main/inse/patents/authors/test_topic_filter.py +++ /dev/null @@ -1,256 +0,0 @@ -import numpy as np -import pytest - -from inse.models.openalex.author import Author -from inse.models.openalex.dehydrated_institution import DehydratedInstitution -from inse.models.openalex.work_topic import WorkTopic -from inse.patents.authors import ipc_topic_matching -from inse.patents.authors.ipc_topic_matching import TopicMatchResult -from inse.patents.authors.topic_filter import ( - decide_patent, - filter_patents_by_author_topics, - to_author_patent_entry, -) -from inse.patents.common import model - - -def _cluster_vector(label: str) -> np.ndarray: - vectors = { - "medical": np.array([1.0, 0.0, 0.0]), - "automotive": np.array([0.0, 1.0, 0.0]), - } - vector = vectors[label] - return vector / np.linalg.norm(vector) - - -def _label_text(text: str) -> str: - lowered = text.lower() - if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire")): - return "automotive" - return "medical" - - -@pytest.fixture(autouse=True) -def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: - def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: - return np.stack([_cluster_vector(_label_text(text)) for text in texts]) - - monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) - - -def _author( - display_name: str, - *topics: str, - institutions: list[str] | None = None, -) -> Author: - return Author( - display_name=display_name, - topics=[ - WorkTopic(display_name=topic, score=1.0 - index * 0.1) - for index, topic in enumerate(topics) - ], - last_known_institutions=[ - DehydratedInstitution(display_name=name) - for name in (institutions or []) - ], - ) - - -def _tire_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: - return model.PatentEntry( - patent_id="EP1", - source="EPO", - title="Vehicle pneumatic tyre and rubber mixture for a tread", - abstract="Automotive tire tread composition for pneumatic tyres.", - inventors=inventors, - assignees=assignees or [], - ipc_descriptions=[ - model.IpcClassification(symbol="B60C", ipc_class="B60 - Vehicles and tyres") - ], - ) - - -def _medical_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: - return model.PatentEntry( - patent_id="EP2", - source="EPO", - title="Cardiac arrhythmia monitoring system", - abstract="Heart rhythm monitoring for coronary artery disease.", - inventors=inventors, - assignees=assignees or [], - ipc_descriptions=[ - model.IpcClassification(symbol="A61B", ipc_class="A61 - Medical or veterinary science") - ], - ) - - -# --- rare names: lenient ------------------------------------------------------ - -def test_rare_name_conflict_rejected() -> None: - author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") - patents = [_tire_patent(inventors=["Uncommon, Xaver"])] - filtered = filter_patents_by_author_topics(patents, author) - assert filtered == [] - - -def test_rare_name_related_topic_kept() -> None: - author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") - patents = [_medical_patent(inventors=["Uncommon, Xaver"])] - filtered = filter_patents_by_author_topics(patents, author) - assert len(filtered) == 1 - assert filtered[0].decision == "keep" - - -# --- common names: strict ----------------------------------------------------- - -def test_common_name_full_name_and_strong_topic_kept() -> None: - author = _author("Christian Weber", "Cardiac arrhythmia disorders") - patents = [_medical_patent(inventors=["Weber, Christian"])] - filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) - assert len(filtered) == 1 - assert filtered[0].decision == "keep" - - -def test_common_name_initial_only_rejected_even_with_strong_topic() -> None: - author = _author("Christian Weber", "Cardiac arrhythmia disorders") - patents = [_medical_patent(inventors=["Weber, C."])] - filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) - assert filtered == [] - - -def test_common_name_conflict_rejected_without_institution() -> None: - author = _author("Christian Weber", "Cardiac arrhythmia disorders") - patents = [_tire_patent(inventors=["Weber, Christian"])] - filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) - assert filtered == [] - - -def test_common_name_institution_match_wins_over_conflict() -> None: - author = _author( - "Christian Weber", - "Cardiac arrhythmia disorders", - institutions=["Boston University"], - ) - patents = [ - _tire_patent(inventors=["Weber, C."], assignees=["Boston University"]) - ] - filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) - assert len(filtered) == 1 - assert filtered[0].institution_match - assert filtered[0].decision == "keep" - - -# --- personal applicant (assignee) ------------------------------------------- - -def test_personal_assignee_match_keeps_patent_via_name_filter() -> None: - from inse.patents.authors.name_matching import filter_patents_by_author_name - - display_name = "Pedro José Marrón" - patent = model.PatentEntry( - patent_id="EP2867692", - source="EPO", - title="Method for generating and using a map", - abstract="Indoor localization map for wireless sensor networks.", - inventors=["Someone Else"], - assignees=["Marrón, Pedro José, Dr."], - ipc_descriptions=[ - model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") - ], - ) - # Name filter keeps it because the person is the applicant. - assert filter_patents_by_author_name([patent], display_name) == [patent] - - -def test_personal_assignee_is_strong_identity_signal() -> None: - author = _author( - "Pedro José Marrón", - "Energy Efficient Wireless Sensor Networks", - ) - patent = model.PatentEntry( - patent_id="EP2867692", - source="EPO", - title="Method for generating and using a map", - abstract="Indoor localization map for wireless sensor networks.", - inventors=["Someone Else"], - assignees=["Marrón, Pedro José, Dr."], - ipc_descriptions=[ - model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") - ], - ) - filtered = filter_patents_by_author_topics([patent], author) - assert len(filtered) == 1 - assert filtered[0].personal_assignee_match - assert filtered[0].decision == "keep" - - -# --- fallback topics ---------------------------------------------------------- - -def test_fallback_topics_enable_conflict_detection() -> None: - author = _author("Xaver Uncommon") # no topics on author document - patents = [_tire_patent(inventors=["Uncommon, Xaver"])] - - without_fallback = filter_patents_by_author_topics(patents, author) - assert len(without_fallback) == 1 # cannot judge topic -> lenient keep - - with_fallback = filter_patents_by_author_topics( - patents, - author, - fallback_topic_names=["Cardiac arrhythmia disorders"], - ) - assert with_fallback == [] # fallback reveals the conflict - - -# --- decision unit tests ------------------------------------------------------ - -def _match(level: str, conflict: bool) -> TopicMatchResult: - return TopicMatchResult(level=level, similarity=0.9, topic_conflict=conflict) - - -def test_decide_common_requires_strong_identity() -> None: - assert decide_patent( - is_common=True, - name_match="full", - institution_match=False, - topic_match=_match("weak", False), - can_judge_topic=True, - ) == "reject" - - assert decide_patent( - is_common=True, - name_match="full", - institution_match=False, - topic_match=_match("strong", False), - can_judge_topic=True, - ) == "keep" - - -def test_decide_institution_always_keeps() -> None: - assert decide_patent( - is_common=True, - name_match="initial", - institution_match=True, - topic_match=_match("none", True), - can_judge_topic=True, - ) == "keep" - - -def test_decide_rare_without_topic_judgement_keeps() -> None: - assert decide_patent( - is_common=False, - name_match="initial", - institution_match=False, - topic_match=_match("none", False), - can_judge_topic=False, - ) == "weaken" - - -# --- response mapping --------------------------------------------------------- - -def test_to_author_patent_entry_exposes_topic_metadata() -> None: - author = _author("Christian Weber", "Cardiac arrhythmia disorders") - patents = [_medical_patent(inventors=["Weber, Christian"])] - filtered = filter_patents_by_author_topics(patents, author)[0] - entry = to_author_patent_entry(filtered) - assert entry.topic_match_level == "strong" - assert entry.topic_filter_decision == "keep" - assert entry.topic_similarity is not None diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py index 49787fd0..a7d0568a 100644 --- a/service/src/main/inse/patents/authors/topic_filter.py +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -1,221 +1,138 @@ -"""Attribute name-matched patents to a person using identity + topic signals. - -Identity signals (institution/assignee match, full given-name match) decide -*whether the patent belongs to the person*. IPC/CPC topic similarity is only a -supporting plausibility signal. The gating is adaptive: - -- rare names: lenient (only clear topic conflicts are dropped) -- common names: strict (a strong identity signal is required) -""" +"""Filter name-matched patents using precomputed IPC/CPC → OpenAlex topic mappings.""" from __future__ import annotations from dataclasses import dataclass -from typing import Literal from inse.models.openalex.author import Author from inse.patents.authors.identity import ( - author_institution_names, - best_name_match_kind, patent_institution_match, patent_personal_assignee_match, ) -from inse.patents.authors.ipc_topic_matching import ( - TopicMatchResult, - author_topic_names, - match_patents_to_topics, - patent_has_topic_signal, +from inse.patents.authors.ipc_openalex_mapping import ( + author_openalex_topic_refs, + load_ipc_openalex_mapping, + patent_topics_match_author, + resolve_mapped_topics_for_patent, ) from inse.patents.common import model -TopicFilterDecision = Literal["keep", "weaken", "reject"] -NameMatchKind = Literal["full", "initial", "none"] - @dataclass(frozen=True) -class FilteredPatent: +class TopicFilterResult: patent: model.PatentEntry - topic_match: TopicMatchResult - decision: TopicFilterDecision - name_match: NameMatchKind + decision: str + matched_via_mapping: bool institution_match: bool - personal_assignee_match: bool = False + personal_assignee_match: bool -def decide_patent( - *, - is_common: bool, - name_match: NameMatchKind, - institution_match: bool, - topic_match: TopicMatchResult, - can_judge_topic: bool, - personal_assignee_match: bool = False, -) -> TopicFilterDecision: - topic_conflict = topic_match.topic_conflict if can_judge_topic else False - topic_strong = (topic_match.level == "strong") if can_judge_topic else False - - # Institution/assignee overlap or the person being the personal applicant - # are the strongest identity signals we have. - if institution_match or personal_assignee_match: - return "keep" - - if is_common: - # Common names need a strong identity signal. A full given-name match - # together with a clearly matching research field is the minimum. - if name_match == "full" and topic_strong: - return "keep" - return "reject" - - # Rare names: lenient. Only drop clear thematic conflicts. - if topic_conflict: - return "reject" - if topic_strong or name_match == "full": - return "keep" - return "weaken" +def _author_has_topic_profile(author: Author) -> bool: + refs = author_openalex_topic_refs(author) + return bool(refs.topic_ids or refs.subfield_ids or refs.field_ids) -def resolve_topic_names( - author: Author, - fallback_topic_names: list[str] | None = None, -) -> list[str]: - topic_names = author_topic_names(author) - if topic_names: - return topic_names - if fallback_topic_names: - return [name for name in fallback_topic_names if name and name.strip()] - return [] - - -_NEUTRAL_TOPIC = TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) - - -def _needs_topic_judgement( - *, - is_common: bool, - name_match: NameMatchKind, - strong_identity: bool, - can_judge_topic: bool, +def _patent_has_mapped_topics( + patent: model.PatentEntry, + mapping, ) -> bool: - # A strong identity signal already decides "keep" without the topic. - if strong_identity: - return False - if not can_judge_topic: - return False - if is_common: - # Common names are only rescued by (full name + strong topic); - # without a full name they are rejected regardless of topic. - return name_match == "full" - # Rare names always consult the topic (conflict / strong check). - return True + return bool(resolve_mapped_topics_for_patent(patent, mapping)) -def filter_patents_by_author_topics( +def _topic_conflict( + patent: model.PatentEntry, + author: Author, + mapping, +) -> bool: + if not _author_has_topic_profile(author): + return False + if not _patent_has_mapped_topics(patent, mapping): + return False + return not patent_topics_match_author(patent, author, mapping) + + +def filter_patents_by_ipc_topic_mapping( patents: list[model.PatentEntry], author: Author, *, is_ambiguous: bool = False, - fallback_topic_names: list[str] | None = None, -) -> list[FilteredPatent]: - topic_names = resolve_topic_names(author, fallback_topic_names) - common_name = is_ambiguous - institution_names = author_institution_names(author) + mapping=None, +) -> list[TopicFilterResult]: + table = mapping if mapping is not None else load_ipc_openalex_mapping() + institution_names = [ + name + for institution in author.last_known_institutions or [] + if (name := getattr(institution, "display_name", None)) + ] + for affiliation in author.affiliations or []: + institution = getattr(affiliation, "institution", None) + if institution is not None and (name := getattr(institution, "display_name", None)): + institution_names.append(name) + display_name = author.display_name or "" - has_author_topics = bool(topic_names) + filtered: list[TopicFilterResult] = [] - # Pre-compute the cheap identity signals so we only run the expensive - # sentence-transformer encoding for patents whose decision truly depends - # on the research topic. - signals = [] - patents_to_encode: list[model.PatentEntry] = [] for patent in patents: - name_match = best_name_match_kind(patent, display_name) 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 - can_judge_topic = has_author_topics and patent_has_topic_signal(patent) + mapped_topics = resolve_mapped_topics_for_patent(patent, table) + matched_via_mapping = patent_topics_match_author(patent, author, table) - needs_topic = _needs_topic_judgement( - is_common=common_name, - name_match=name_match, - strong_identity=strong_identity, - can_judge_topic=can_judge_topic, - ) - if needs_topic: - patents_to_encode.append(patent) - signals.append( - (name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic) - ) - - topic_by_patent_id = {} - if patents_to_encode: - encoded_matches = match_patents_to_topics(patents_to_encode, topic_names) - topic_by_patent_id = { - id(patent): match - for patent, match in zip(patents_to_encode, encoded_matches) - } - - filtered: list[FilteredPatent] = [] - for patent, signal in zip(patents, signals): - name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic = signal - topic_match = topic_by_patent_id.get(id(patent), _NEUTRAL_TOPIC) if needs_topic else _NEUTRAL_TOPIC - - decision = decide_patent( - is_common=common_name, - name_match=name_match, - institution_match=institution_match, - personal_assignee_match=personal_assignee_match, - topic_match=topic_match, - can_judge_topic=can_judge_topic and needs_topic, - ) - if decision == "reject": + if strong_identity: + filtered.append( + TopicFilterResult( + patent=patent, + decision="keep", + matched_via_mapping=matched_via_mapping, + institution_match=institution_match, + personal_assignee_match=personal_assignee_match, + ) + ) continue + + if is_ambiguous: + if matched_via_mapping: + filtered.append( + TopicFilterResult( + patent=patent, + decision="keep", + matched_via_mapping=True, + institution_match=False, + personal_assignee_match=False, + ) + ) + continue + + if _topic_conflict(patent, author, table): + continue + filtered.append( - FilteredPatent( + TopicFilterResult( patent=patent, - topic_match=topic_match, - decision=decision, - name_match=name_match, - institution_match=institution_match, - personal_assignee_match=personal_assignee_match, + decision="keep", + matched_via_mapping=matched_via_mapping, + institution_match=False, + personal_assignee_match=False, ) ) filtered.sort( key=lambda item: ( - item.decision != "keep", + not item.matched_via_mapping, not (item.institution_match or item.personal_assignee_match), - -item.topic_match.similarity, item.patent.publication_date or "", ), + reverse=False, ) return filtered -def to_author_patent_entry(filtered: FilteredPatent) -> model.AuthorPatentEntry: - return model.AuthorPatentEntry( - **filtered.patent.model_dump(), - topic_similarity=filtered.topic_match.similarity or None, - topic_match_level=_response_match_level(filtered), - topic_filter_decision=( - "keep" if filtered.decision == "keep" else "weaken" - ), - ) - - -def patent_from_filtered(entry: model.AuthorPatentEntry) -> model.PatentEntry: - return model.PatentEntry( - **entry.model_dump( - exclude={ - "topic_similarity", - "topic_match_level", - "topic_filter_decision", - } - ) - ) - - -def _response_match_level(filtered: FilteredPatent) -> model.TopicMatchLevel: - if filtered.decision == "keep": - return "strong" - if filtered.decision == "weaken": - return "weak" - return "unknown" +def finest_mapped_topic_label( + patent: model.PatentEntry, + mapping=None, +) -> str | None: + table = mapping if mapping is not None else load_ipc_openalex_mapping() + mapped = resolve_mapped_topics_for_patent(patent, table) + if not mapped: + return None + return mapped[0].topic_display_name or mapped[0].topic_id diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index 783f6189..b3cc97a4 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -1,5 +1,3 @@ -from typing import Literal - from pydantic import BaseModel, ConfigDict, Field @@ -36,21 +34,11 @@ class PatentEntry(BaseModel): country: str | None = None -TopicMatchLevel = Literal["strong", "weak", "unknown"] -TopicFilterDecision = Literal["keep", "weaken"] - - -class AuthorPatentEntry(PatentEntry): - topic_similarity: float | None = None - topic_match_level: TopicMatchLevel | None = None - topic_filter_decision: TopicFilterDecision | None = None - - class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[AuthorPatentEntry] + patents: list[PatentEntry] class PatentsByInstitutionResponse(BaseModel): diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index 92af655f..828a1082 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -133,6 +133,9 @@ def test_first_name_match_kind() -> None: ("Mohamed Ali Hassan", "Mohamed Ali Hassan", True), ("Ali Hassan", "Mohamed Ali Hassan", True), ("Karem C Weber", "Christian Weber", False), + ("Schmitz, Oliver", "Oliver J. Schmitz", False), + ("Schmitz, Oliver J.", "Oliver J. Schmitz", True), + ("Schmitz, O. J.", "Oliver J. Schmitz", True), ], ) def test_name_matches_person_multi_part( @@ -161,6 +164,19 @@ def test_first_name_match_kind_multi_part() -> None: ) +def test_middle_initial_requires_corroboration() -> None: + assert not name_matches_person("Schmitz, Oliver", "Oliver J. Schmitz") + assert name_matches_person("Schmitz, Oliver J.", "Oliver J. Schmitz") + assert ( + first_name_match_kind_for_person("Schmitz, Oliver", "Oliver J. Schmitz") + == "none" + ) + assert ( + first_name_match_kind_for_person("Schmitz, Oliver J.", "Oliver J. Schmitz") + == "full" + ) + + def test_search_name_variants_includes_initial() -> None: variants = search_name_variants("Christian") assert "C" in variants diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 754f3fa1..cdcc5f97 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -283,24 +283,6 @@ async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics -async def get_topic_names_for_author(author_id: str) -> list[str]: - """Return the author's primary research topic names from the works aggregation. - - Used as a fallback when the author document has no populated ``topics`` field. - """ - short_id = author_id.replace("https://openalex.org/", "").strip() - try: - _works, topics = await _fetch_works_and_topics(short_id) - except Exception as exc: # noqa: BLE001 - logger.warning("Failed to fetch fallback topics for author %s: %s", short_id, exc) - return [] - return [ - topic["display_name"] - for topic in topics - if topic.get("display_name") - ] - - async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index f7f2f2df..5565ab9a 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -32,12 +32,3 @@ export interface PatentEntry { country?: string | null; } -export type TopicMatchLevel = 'strong' | 'weak' | 'unknown'; -export type TopicFilterDecision = 'keep' | 'weaken'; - -export interface AuthorPatentEntry extends PatentEntry { - topic_similarity?: number | null; - topic_match_level?: TopicMatchLevel | null; - topic_filter_decision?: TopicFilterDecision | null; -} - diff --git a/webapp/src/app/api/model/patentsByAuthorResponse.ts b/webapp/src/app/api/model/patentsByAuthorResponse.ts index 70eef4bc..622d3920 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -7,12 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthorPatentEntry } from './patentEntry'; +import { PatentEntry } from './patentEntry'; export interface PatentsByAuthorResponse { author_id: string; author_name?: string | null; patent_count: number; - patents: Array; + patents: Array; } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index ac603aae..8c558bee 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -4,6 +4,7 @@ import { superAdminGuard } from './shared/guards/super-admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; import { personBioResolver } from './resolvers/person-bio.resolver'; +import { personPatentsResolver } from './resolvers/person-patents.resolver'; import { personResolver } from './resolvers/person.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; @@ -204,6 +205,7 @@ export const routes: Routes = [ resolve: { personData: personResolver, personBio: personBioResolver, + personPatents: personPatentsResolver, }, runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'], children: [ 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 8d9b20c9..b92b2cf2 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,8 +1,10 @@ -import { Component, OnInit, inject } from '@angular/core'; +import { Component, DestroyRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService } from '../../api/api/patents.service'; -import { AuthorPatentEntry } from '../../api/model/patentEntry'; +import { finalize, of, switchMap } from 'rxjs'; +import { PatentEntry } from '../../api/model/patentEntry'; +import { PersonPatentsResolved } from '../../resolvers/person-patents.resolver'; import { formatPatentDate, getPublicationStageLabel, @@ -17,15 +19,15 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO'; templateUrl: './person-patents.component.html', styleUrl: './person-patents.component.scss', }) -export class PersonPatentsComponent implements OnInit { +export class PersonPatentsComponent { private route = inject(ActivatedRoute); private router = inject(Router); - private patentsApi = inject(PatentsService); + private destroyRef = inject(DestroyRef); - patents: AuthorPatentEntry[] = []; - filteredPatents: AuthorPatentEntry[] = []; + patents: PatentEntry[] = []; + filteredPatents: PatentEntry[] = []; authorName: string | null = null; - selectedPatent: AuthorPatentEntry | null = null; + selectedPatent: PatentEntry | null = null; loading = true; error = false; @@ -36,35 +38,47 @@ export class PersonPatentsComponent implements OnInit { selectedPage = 1; readonly pageSize = 10; - ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; + constructor() { + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); - const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } - if (this.isValidFilter(filterFromUrl)) { - this.activeFilter = filterFromUrl; - } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; - } + this.route.parent?.data + .pipe( + switchMap((data) => { + const resolved = data['personPatents'] as + | PersonPatentsResolved + | undefined; + if (!resolved?.patents$) { + return of(null); + } - if (authorId) { - this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ - next: (result) => { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.applyFilter(); - this.loading = false; - }, - error: () => { - this.error = true; - this.loading = false; - }, - }); - } - }); + this.loading = true; + this.error = false; + return resolved.patents$.pipe( + finalize(() => { + this.loading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((result) => { + if (!result) { + this.error = true; + return; + } + + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + }); } setFilter(filter: SourceFilter): void { @@ -81,7 +95,7 @@ export class PersonPatentsComponent implements OnInit { this.updateQueryParams(); } - selectPatent(patent: AuthorPatentEntry): void { + selectPatent(patent: PatentEntry): void { this.selectedPatent = patent; this.updateQueryParams(); } @@ -101,7 +115,7 @@ export class PersonPatentsComponent implements OnInit { this.filteredPatents = this.sortPatents(patents); } - private sortPatents(patents: AuthorPatentEntry[]): AuthorPatentEntry[] { + private sortPatents(patents: PatentEntry[]): PatentEntry[] { return [...patents].sort((a, b) => { if (this.sortMode === 'date') { return (b.publication_date ?? '').localeCompare( @@ -134,7 +148,7 @@ export class PersonPatentsComponent implements OnInit { return value === 'date' || value === 'title'; } - getPagedPatents(): AuthorPatentEntry[] { + getPagedPatents(): PatentEntry[] { const start = (this.selectedPage - 1) * this.pageSize; return this.filteredPatents.slice(start, start + this.pageSize); } @@ -164,7 +178,7 @@ export class PersonPatentsComponent implements OnInit { return this.patents.filter((p) => p.source === 'USPTO').length; } - trackPatent(_index: number, patent: AuthorPatentEntry): string { + trackPatent(_index: number, patent: PatentEntry): string { return [ patent.source, patent.patent_id, @@ -184,7 +198,7 @@ export class PersonPatentsComponent implements OnInit { return `${text.slice(0, 160).trimEnd()}…`; } - getPublicationStageLabel(patent: AuthorPatentEntry): string | null { + getPublicationStageLabel(patent: PatentEntry): string | null { return getPublicationStageLabel(patent); } diff --git a/webapp/src/app/resolvers/person-patents.resolver.ts b/webapp/src/app/resolvers/person-patents.resolver.ts new file mode 100644 index 00000000..5008d36d --- /dev/null +++ b/webapp/src/app/resolvers/person-patents.resolver.ts @@ -0,0 +1,27 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { Observable, of, catchError, shareReplay } from 'rxjs'; +import { PatentsByAuthorResponse, PatentsService } from '../api'; + +export interface PersonPatentsResolved { + patents$: Observable; +} + +export const personPatentsResolver: ResolveFn = (route) => { + const authorId = route.paramMap.get('id'); + const patentsApi = inject(PatentsService); + + if (!authorId) { + return { patents$: of(null) }; + } + + const patents$ = patentsApi.getPatentsByAuthor(authorId, 'body').pipe( + catchError((err) => { + console.error('Failed to load patents:', err); + return of(null); + }), + shareReplay(1), + ); + + return { patents$ }; +}; From 5d22b201e941c6e0ae29e9427582e83fec7cd113 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 08:50:48 +0200 Subject: [PATCH 16/60] publications/persons: add open-institution shortcut to institution tags and filter chips --- .../person-card/person-card.component.html | 8 +++++ .../person-card/person-card.component.scss | 25 +++++++++++++ .../person-card/person-card.component.ts | 20 +++++++++-- .../person-list/person-list.component.html | 8 +++++ .../person-list/person-list.component.scss | 21 +++++++++++ .../person-list/person-list.component.ts | 35 +++++++++++++++++++ .../person-publications.component.html | 12 +++++++ .../person-publications.component.scss | 23 ++++++++++++ .../person-publications.component.ts | 13 +++++++ 9 files changed, 163 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 946430ae..1f7741d4 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -95,6 +95,14 @@ >{{ inst.country_code.toUpperCase() }} } + @if (institutionPageId() && !loading()) { + open_in_new + }
} diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 75f0ed69..2172cd99 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -162,6 +162,31 @@ white-space: nowrap; } + .institution-open-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-left: 5px; + font-size: 12px; + line-height: 1; + vertical-align: middle; + cursor: pointer; + opacity: 0; + transition: opacity 0.15s ease; + + &:hover { + opacity: 1; + } + } + + &:hover .institution-open-icon { + opacity: 0.7; + + &:hover { + opacity: 1; + } + } + &:hover, &:focus-visible { background: var(--sg-primary); diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index e8a50711..aef4cd8f 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -1,6 +1,6 @@ -import { Component, input, computed, output } from '@angular/core'; +import { Component, inject, input, computed, output } from '@angular/core'; import { CommonModule } from '@angular/common'; -import { RouterLink } from '@angular/router'; +import { Router, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; @@ -23,6 +23,8 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; styleUrl: './person-card.component.scss', }) export class PersonCardComponent { + private readonly router = inject(Router); + person = input.required(); isBookmarked = input(false); loading = input(false); @@ -66,6 +68,20 @@ export class PersonCardComponent { return newestInstitution; }); + institutionPageId = computed( + () => this.institution()?.id?.split('/').pop() ?? null, + ); + + openInstitutionPage(event: Event): void { + event.stopPropagation(); + event.preventDefault(); + + const id = this.institutionPageId(); + if (!id) return; + + void this.router.navigate(['/institution', id]); + } + isInstitutionActive = computed(() => { const active = this.activeInstitutionName().trim().toLowerCase(); if (!active) return false; diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 0dc9fe14..9647b24a 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -82,6 +82,14 @@ filter.countryCode.toUpperCase() }} } + @if (findInstitutionPageIdByName(filter.value)) { + open_in_new + } } @empty { - diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index 45f2e235..715913f9 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -301,6 +301,29 @@ h2 { font-size: 9px; } +.filter-institution-chip .institution-open-icon, +.publication-institution-tag .institution-open-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-left: 5px; + font-size: 12px; + line-height: 1; + cursor: pointer; + opacity: 0; + transition: opacity 0.15s ease; +} + +.filter-institution-chip:hover .institution-open-icon, +.publication-institution-tag:hover .institution-open-icon { + opacity: 0.7; +} + +.filter-institution-chip .institution-open-icon:hover, +.publication-institution-tag .institution-open-icon:hover { + opacity: 1; +} + .filter-meta-chip__label, .filter-topic-chip__label { overflow: hidden; diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index 739602b2..09a9d755 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -486,6 +486,19 @@ export class PersonPublicationsComponent implements OnInit { }); } + openInstitutionPage( + institutionId: string | null | undefined, + event: Event, + ): void { + event.stopPropagation(); + event.preventDefault(); + + const id = institutionId?.split('/').pop(); + if (!id) return; + + void this.router.navigate(['/institution', id]); + } + getSelectedTopicTooltip(topic: TopicAutocompleteOption): string { const workTopic = this.findPublicationTopic(topic.id); From bb941361a154fba94aded0fcfb081f1aad536efc Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 09:04:43 +0200 Subject: [PATCH 17/60] publication-detail: link topic chips to keywords topic mapping --- .../publication-detail.component.html | 3 ++- .../publication-detail.component.ts | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index c672c74c..54f34606 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -182,7 +182,8 @@ [subfieldName]="topic.subfield?.display_name" [fieldName]="topic.field?.display_name" [domainName]="topic.domain?.display_name" - [color]="getTopicColor(topic)"> + [color]="getTopicColor(topic)" + (chipClick)="openTopicInKeywords(topic)"> }
diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index b377543b..c0c1ee5e 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -6,7 +6,7 @@ import { HttpClient } from '@angular/common/http'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; -import { ActivatedRoute, RouterLink } from '@angular/router'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { finalize } from 'rxjs'; import { Authorship, @@ -50,6 +50,7 @@ export class PublicationDetailComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly httpClient = inject(HttpClient); private readonly location = inject(Location); + private readonly router = inject(Router); private readonly worksService = inject(WorksService); publication: Work | null = null; @@ -75,6 +76,22 @@ export class PublicationDetailComponent implements OnInit { this.location.back(); } + openTopicInKeywords(topic: WorkTopic): void { + const topicName = topic.display_name?.trim(); + if (!topicName) return; + + // Deep link into the keywords page: the topic lands as manual keyword, + // is preselected and shown in the topic-mapping view, so the + // analysis/visualization can be started for it directly. + void this.router.navigate(['/keywords'], { + queryParams: { + manual: topicName, + selected: topicName, + view: 'topic', + }, + }); + } + getTopicColor(topic: WorkTopic): string { return topicHierarchyColor({ id: topic.id, From 383c77134a7ab8cecf3e3effa7fae79060c3df66 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 09:19:34 +0200 Subject: [PATCH 18/60] publication-detail: link topic chips to person search topic filter --- .../publication-detail.component.html | 2 +- .../publication-detail.component.ts | 15 +++++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 54f34606..a91f0a45 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -183,7 +183,7 @@ [fieldName]="topic.field?.display_name" [domainName]="topic.domain?.display_name" [color]="getTopicColor(topic)" - (chipClick)="openTopicInKeywords(topic)"> + (chipClick)="findAuthorsForTopic(topic)"> } diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index c0c1ee5e..b4c766e8 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -76,19 +76,14 @@ export class PublicationDetailComponent implements OnInit { this.location.back(); } - openTopicInKeywords(topic: WorkTopic): void { + findAuthorsForTopic(topic: WorkTopic): void { const topicName = topic.display_name?.trim(); if (!topicName) return; - // Deep link into the keywords page: the topic lands as manual keyword, - // is preselected and shown in the topic-mapping view, so the - // analysis/visualization can be started for it directly. - void this.router.navigate(['/keywords'], { - queryParams: { - manual: topicName, - selected: topicName, - view: 'topic', - }, + // Deep link into the person search with this topic preset as filter, + // so matching authors show up directly. + void this.router.navigate(['/persons'], { + queryParams: { topic: topicName }, }); } From e470b65b5a18c64232e8c293bae7985ac3b194be Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 09:38:06 +0200 Subject: [PATCH 19/60] publication-detail: make authors and institutions collapsible like news sidebar --- .../publication-detail.component.html | 197 +++++++++++------- .../publication-detail.component.scss | 85 ++++++++ .../publication-detail.component.ts | 5 + 3 files changed, 208 insertions(+), 79 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index a91f0a45..77157e33 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -117,55 +117,75 @@
} -
-
+
+
-
- @for (authorship of authors(); track authorship.author?.id) { - - } @empty { -

Keine Angaben vorhanden.

+ Autorinnen und Autoren + info_outline + @if (authors().length) { + {{ authors().length }} } -
+ expand_more + + @if (authorsExpanded) { +
+
+ @for (authorship of authors(); track authorship.author?.id) { + + } @empty { +

Keine Angaben vorhanden.

+ } +
+
+ }
@if (publication.topics?.length) { @@ -300,41 +320,60 @@ @if (institutions().length) { -
-
+
+
-
- @for (institution of institutions(); track institution.id) { -
- - {{ institution.name }} - - @if (institution.country) { - - - {{ institution.country.toUpperCase() }} - - } @else if (institution.type) { - {{ institution.type }} + Institutionen + info_outline + {{ institutions().length }} + expand_more + + @if (institutionsExpanded) { +
+
+ @for (institution of institutions(); track institution.id) { +
+ + {{ institution.name }} + + @if (institution.country) { + + + {{ institution.country.toUpperCase() }} + + } @else if (institution.type) { + {{ institution.type }} + } +
}
- } -
+
+ }
} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss index 2e8c72d4..463604b8 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.scss +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -188,6 +188,79 @@ aside { box-shadow: var(--sg-shadow-sm); } +.accordion-card { + padding: 0; + overflow: hidden; +} + +.accordion-header { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + padding: 18px 22px; + background: none; + border: none; + cursor: pointer; + text-align: left; + font-family: inherit; + font-size: 16px; + font-weight: 700; + color: var(--sg-text); + transition: background 0.12s; + + &:hover { + background: #f6f9ff; + } + + mat-icon { + flex-shrink: 0; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--sg-text-muted); + } +} + +.accordion-title { + flex: 1; +} + +.count-badge { + padding: 2px 7px; + border-radius: 999px; + background: #e8effe; + color: #3b5bd6; + font-size: 11px; + font-weight: 700; +} + +.info-icon { + flex-shrink: 0; + width: 16px !important; + height: 16px !important; + font-size: 16px !important; + color: var(--sg-text-muted); + opacity: 0.7; + cursor: default; + + &:hover { + opacity: 1; + } +} + +.chevron { + transition: transform 0.2s ease; + + &.rotated { + transform: rotate(-90deg); + } +} + +.accordion-body { + padding: 4px 22px 22px; +} + .section-title { display: flex; align-items: center; @@ -445,6 +518,18 @@ dd { padding: 22px 20px; } + .accordion-card { + padding: 0; + } + + .accordion-header { + padding: 16px 20px; + } + + .accordion-body { + padding: 4px 20px 20px; + } + .metrics, .author-list { grid-template-columns: 1fr; diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index b4c766e8..a039137b 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -6,6 +6,7 @@ import { HttpClient } from '@angular/common/http'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { finalize } from 'rxjs'; import { @@ -38,6 +39,7 @@ interface InstitutionDetail { MatButtonModule, MatIconModule, MatProgressSpinnerModule, + MatTooltipModule, RouterLink, TopicChipComponent, UpperCasePipe, @@ -57,6 +59,9 @@ export class PublicationDetailComponent implements OnInit { loading = true; notFound = false; + authorsExpanded = true; + institutionsExpanded = false; + ngOnInit(): void { this.loading = true; From 940c050cd72a14d224c35b352771c68566562f6a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 09:44:17 +0200 Subject: [PATCH 20/60] publication-detail: make sources and funding sections collapsible --- .../publication-detail.component.html | 168 +++++++++++------- .../publication-detail.component.ts | 9 + 2 files changed, 113 insertions(+), 64 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 77157e33..7c11115c 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -225,52 +225,71 @@ } @if (sources().length) { -
-
+
+
-
- @for ( - location of sources(); - track location.source?.id || location.landing_page_url - ) { -
-
- {{ - location.source?.display_name || 'Externe Quelle' - }} -

- {{ - location.version || - location.source?.type || - 'Veröffentlichte Version' - }} - @if (location.license) { - · {{ location.license }} - } -

-
-
- @if (location.is_oa) { - Open Access - } - @if ( - location.pdf_url || location.landing_page_url; - as sourceUrl - ) { - - open_in_new - - } -
-
- } -
+ Quellen und Versionen + info_outline + {{ sources().length }} + expand_more + + @if (sourcesExpanded) { +
+
+ @for ( + location of sources(); + track location.source?.id || location.landing_page_url + ) { +
+
+ {{ + location.source?.display_name || 'Externe Quelle' + }} +

+ {{ + location.version || + location.source?.type || + 'Veröffentlichte Version' + }} + @if (location.license) { + · {{ location.license }} + } +

+
+
+ @if (location.is_oa) { + Open Access + } + @if ( + location.pdf_url || location.landing_page_url; + as sourceUrl + ) { + + open_in_new + + } +
+
+ } +
+
+ }
} @@ -378,27 +397,48 @@ } @if (publication.funders?.length || publication.awards?.length) { -
-
+
+
-
- @for (funder of publication.funders ?? []; track funder.id) { -
- {{ funder.display_name }}Förderorganisation + Förderungen + info_outline + {{ fundingCount() }} + expand_more + + @if (fundingExpanded) { +
+
+ @for (funder of publication.funders ?? []; track funder.id) { +
+ {{ funder.display_name }}Förderorganisation +
+ } + @for (award of publication.awards ?? []; track award.id) { +
+ {{ + award.display_name || award.funder_award_id + }}{{ + award.funder_display_name || 'Förderung' + }} +
+ }
- } - @for (award of publication.awards ?? []; track award.id) { -
- {{ - award.display_name || award.funder_award_id - }}{{ award.funder_display_name || 'Förderung' }} -
- } -
+
+ }
} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index a039137b..6b8d27a4 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -61,6 +61,8 @@ export class PublicationDetailComponent implements OnInit { authorsExpanded = true; institutionsExpanded = false; + sourcesExpanded = false; + fundingExpanded = false; ngOnInit(): void { this.loading = true; @@ -172,6 +174,13 @@ export class PublicationDetailComponent implements OnInit { ); } + fundingCount(): number { + return ( + (this.publication?.funders?.length ?? 0) + + (this.publication?.awards?.length ?? 0) + ); + } + pages(): string | null { const first = this.publication?.biblio?.first_page; const last = this.publication?.biblio?.last_page; From a8e582cf23a5334121bc7d96f8abfaf676d3b8a1 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 7 Jul 2026 09:46:53 +0200 Subject: [PATCH 21/60] publication-detail: make external links section collapsible --- .../publication-detail.component.html | 43 +++++++++++++------ .../publication-detail.component.ts | 1 + 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 7c11115c..54cdc042 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -443,19 +443,38 @@ } @if (externalLinks().length) { -
-
+
+
- + Externe Links + info_outline + {{ externalLinks().length }} + expand_more + + @if (linksExpanded) { +
+ +
+ }
} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index 6b8d27a4..72552ecc 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -63,6 +63,7 @@ export class PublicationDetailComponent implements OnInit { institutionsExpanded = false; sourcesExpanded = false; fundingExpanded = false; + linksExpanded = false; ngOnInit(): void { this.loading = true; From 2b1aa8d9e300b9d108748842b6b732da3dc36a09 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 11:34:43 +0200 Subject: [PATCH 22/60] added file upload backend logic + content extraction from pdf files --- service/Dockerfile | 3 +- .../src/main/inse/keywords/extract_text.py | 95 +++++++++++++++++++ service/src/main/inse/keywords/logic.py | 91 ++++++++++++------ service/src/main/inse/keywords/model.py | 11 +++ service/src/main/inse/keywords/service.py | 4 +- webapp/src/app/api/.openapi-generator/FILES | 2 + 6 files changed, 172 insertions(+), 34 deletions(-) create mode 100644 service/src/main/inse/keywords/extract_text.py diff --git a/service/Dockerfile b/service/Dockerfile index e32d005c..3fe46ebb 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "websockets==12.0" \ "partial-json-parser==0.2.1.1.post7" \ "sqlmodel~=0.0.33" \ - "argon2-cffi~=25.1.0" + "argon2-cffi~=25.1.0" \ + "pypdf==6.14.2" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/src/main/inse/keywords/extract_text.py b/service/src/main/inse/keywords/extract_text.py new file mode 100644 index 00000000..f13d8537 --- /dev/null +++ b/service/src/main/inse/keywords/extract_text.py @@ -0,0 +1,95 @@ +# inse/keywords/file_extraction.py +import base64 +import logging +import httpx +from bs4 import BeautifulSoup +# import fitz +import io +from pypdf import PdfReader +from pypdf.errors import PdfReadError + +logger = logging.getLogger(__name__) + + + +# def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str: +# try: +# raw = base64.b64decode(content_base64) +# except Exception: +# logger.warning("Failed to decode base64 for %s", filename) +# return f"[{filename}: could not decode upload]" + +# if mime_type == "application/pdf" or filename.lower().endswith(".pdf"): +# return _extract_pdf_text(filename, raw) + +# try: +# return raw.decode("utf-8", errors="replace") +# except Exception: +# logger.warning("Failed to decode %s as text", filename) +# return f"[{filename}: unsupported or undecodable content]" + + +# def _extract_pdf_text(filename: str, raw: bytes) -> str: +# try: +# doc = fitz.open(stream=raw, filetype="pdf") +# except Exception as e: +# logger.warning("Failed to open PDF %s: %s", filename, e) +# return f"[{filename}: PDF could not be opened (corrupted or invalid)]" + +# parts = [] +# for page_num in range(len(doc)): +# try: +# parts.append(doc.load_page(page_num).get_text()) +# except Exception as e: +# logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e) +# parts.append(f"[Page {page_num + 1} could not be extracted]") + +# doc.close() +# return "\n".join(parts) +# inse/keywords/file_extraction.py + +def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str: + try: + raw = base64.b64decode(content_base64) + except Exception: + logger.warning("Failed to decode base64 for %s", filename) + return f"[{filename}: could not decode upload]" + + if mime_type == "application/pdf" or filename.lower().endswith(".pdf"): + return _extract_pdf_text(filename, raw) + + try: + return raw.decode("utf-8", errors="replace") + except Exception: + logger.warning("Failed to decode %s as text", filename) + return f"[{filename}: unsupported or undecodable content]" + + +def _extract_pdf_text(filename: str, raw: bytes) -> str: + try: + reader = PdfReader(io.BytesIO(raw), strict=False) # non-strict: tolerate minor spec violations + except Exception as e: + logger.warning("Failed to open PDF %s: %s", filename, e) + return f"[{filename}: PDF could not be opened (corrupted or invalid)]" + + if reader.is_encrypted: + try: + # Attempt to decrypt with an empty password (common for "owner-locked" + # PDFs that don't require one to read content) + reader.decrypt("") + except Exception as e: + logger.warning("Encrypted PDF %s could not be decrypted: %s", filename, e) + return f"[{filename}: PDF is encrypted and could not be read]" + + parts = [] + for page_num, page in enumerate(reader.pages): + try: + parts.append(page.extract_text() or "") + except PdfReadError as e: + logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e) + parts.append(f"[Page {page_num + 1} could not be extracted]") + except Exception as e: + logger.warning("Unexpected error extracting page %d of %s: %s", page_num, filename, e) + parts.append(f"[Page {page_num + 1} could not be extracted]") + + return "\n".join(parts) \ No newline at end of file diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index e329fb56..926cf866 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -23,7 +23,9 @@ from inse.keywords.model import ( KeywordEntry, KeywordEntryWithTopic, KeywordsWsEvent, + FileUpload, ) +from inse.keywords.extract_text import extract_text_from_upload from inse.topics.logic import vector_search_topics_batch logger = logging.getLogger(__name__) EventCallback = Callable[[dict], Awaitable[None]] @@ -64,7 +66,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor """ start_time = time.time() if mode == "url": - text = await _get_text_content(query) + text = await get_text_from_url(query) system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT else: @@ -97,34 +99,6 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time) -async def _get_text_content(url: str) -> str: - """ - Fetches the HTML content from the given URL using httpx and extracts visible text. - """ - try: - headers = { - "User-Agent": ( - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " - "AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/91.0.4472.124 Safari/537.36" - ) - } - async with httpx.AsyncClient(timeout=30.0) as client: - response = await client.get(url, headers=headers) - response.raise_for_status() - - soup = BeautifulSoup(response.text, "html.parser") - for element in soup(["script", "style"]): - element.decompose() - text = soup.get_text(separator=" ", strip=True) - text = " ".join(text.split()) - return text - - except httpx.HTTPError as e: - logger.error(f"HTTP error for {url}: {e}") - except Exception as e: - logger.error(f"Error processing {url}: {e}") - async def extract_keywords_stream_enriched( @@ -132,6 +106,7 @@ async def extract_keywords_stream_enriched( mode: str, limit: int, emit: EventCallback, + files: List[FileUpload] | None = None, ) -> ExtractedKeywordsResponse: start_time = time.time() timeout_seconds = 120 @@ -139,13 +114,24 @@ async def extract_keywords_stream_enriched( if mode == "url": await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump()) - text = await _get_text_content(query) + text = await get_text_from_url(query) if text: await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) else: await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump()) raise RuntimeError(f"Failed to fetch content from {query}") system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT + + elif mode == "files": + await emit(KeywordsWsEvent(type="status", step="extracting_files", message=f"Extrahiere Inhalt aus {len(files or [])} Datei(en)").model_dump()) + text = await _get_files_text(files or []) + print(f"Extracted text from files: {text[:100]}...") # Log the first 100 characters of the extracted text + if not text.strip(): + await emit(KeywordsWsEvent(type="error", message="Kein Text konnte aus den Dateien extrahiert werden").model_dump()) + raise RuntimeError("Failed to extract text from uploaded files") + await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) + system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT + else: text = query await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump()) @@ -298,4 +284,47 @@ async def extract_keywords_stream_enriched( duration=elapsed_time, ) - return result \ No newline at end of file + return result + + +async def get_text_from_url(url: str) -> str: + """ + Fetches the HTML content from the given URL using httpx and extracts visible text. + """ + try: + headers = { + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/91.0.4472.124 Safari/537.36" + ) + } + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.get(url, headers=headers) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "html.parser") + for element in soup(["script", "style"]): + element.decompose() + text = soup.get_text(separator=" ", strip=True) + text = " ".join(text.split()) + return text + + except httpx.HTTPError as e: + logger.error(f"HTTP error for {url}: {e}") + except Exception as e: + logger.error(f"Error processing {url}: {e}") + + +async def _get_files_text(files: List[FileUpload]) -> str: + """ + Extracts and joins text from uploaded files. Runs blocking PDF parsing + in a thread so it doesn't stall the event loop. + """ + parts = [] + for f in files: + text = await asyncio.to_thread( + extract_text_from_upload, f.filename, f.content_base64, f.mime_type + ) + parts.append(text) + return "\n\n---\n\n".join(parts) \ No newline at end of file diff --git a/service/src/main/inse/keywords/model.py b/service/src/main/inse/keywords/model.py index d2c9239e..f8607a7a 100644 --- a/service/src/main/inse/keywords/model.py +++ b/service/src/main/inse/keywords/model.py @@ -8,10 +8,21 @@ from typing import List, Literal from pydantic import BaseModel, Field from inse.topics.model import KeywordTopicMatch + +class FileUpload(BaseModel): + filename: str = Field(description="The name of the uploaded file.") + content_base64: str = Field(description="The base64-encoded content of the uploaded file.") + mime_type: str = Field(description="The MIME type of the uploaded file, e.g., 'application/pdf', 'image/png', etc.") + class KeywordsRequest(BaseModel): query: str = Field(description="The input text from which to extract keywords.") + files: list[FileUpload] | None = None mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.") limit: int = Field(default=None, description="The maximum number of keywords to extract.") +# class KeywordsRequest(BaseModel): +# query: str = Field(description="The input text from which to extract keywords.") +# mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.") +# limit: int = Field(default=None, description="The maximum number of keywords to extract.") class KeywordEntry(BaseModel): keyword: str = Field(description="The extracted keyword.") diff --git a/service/src/main/inse/keywords/service.py b/service/src/main/inse/keywords/service.py index f4de6cf5..76e49a14 100644 --- a/service/src/main/inse/keywords/service.py +++ b/service/src/main/inse/keywords/service.py @@ -51,12 +51,13 @@ async def extract_keywords_ws(websocket: WebSocket): try: raw = await websocket.receive_json() request = KeywordsRequest(**raw) - + logger.info("Received keyword extraction request: %s", request) extraction_task = asyncio.create_task( logic.extract_keywords_stream_enriched( query=request.query, mode=request.mode, limit=request.limit, + files=request.files, emit=emit, ) ) @@ -71,7 +72,6 @@ async def extract_keywords_ws(websocket: WebSocket): except (WebSocketDisconnect, ClientDisconnected): disconnected.set() logger.info("Client disconnected from keyword extraction ws") - print("Client disconnected from keyword extraction ws") except Exception as e: disconnected.set() diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 9928d2c3..65898fe8 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -80,6 +80,7 @@ model/euProjectData.ts model/extractedKeywords.ts model/extractedKeywordsLLM.ts model/extractedKeywordsResponse.ts +model/fileUpload.ts model/filterInformation.ts model/filterProperties.ts model/fp7EurosciVoc.ts @@ -142,6 +143,7 @@ model/loginResponse.ts model/longitude.ts model/matchedAuthor.ts model/matchedOfficer.ts +model/matchedTopic.ts model/mentionedPerson.ts model/meta.ts model/model2YrMeanCitedness.ts From 40610c94c58c2e122d6039da26460e55031e6696 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 11:34:56 +0200 Subject: [PATCH 23/60] regenerated services --- webapp/src/app/api/model/fileUpload.ts | 26 +++++++++++++++++ webapp/src/app/api/model/keywordsRequest.ts | 32 ++++++++++++--------- 2 files changed, 44 insertions(+), 14 deletions(-) create mode 100644 webapp/src/app/api/model/fileUpload.ts diff --git a/webapp/src/app/api/model/fileUpload.ts b/webapp/src/app/api/model/fileUpload.ts new file mode 100644 index 00000000..61722b2f --- /dev/null +++ b/webapp/src/app/api/model/fileUpload.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface FileUpload { + /** + * The name of the uploaded file. + */ + filename: string; + /** + * The base64-encoded content of the uploaded file. + */ + content_base64: string; + /** + * The MIME type of the uploaded file, e.g., \'application/pdf\', \'image/png\', etc. + */ + mime_type: string; +} + diff --git a/webapp/src/app/api/model/keywordsRequest.ts b/webapp/src/app/api/model/keywordsRequest.ts index 1860b68b..8acb7082 100644 --- a/webapp/src/app/api/model/keywordsRequest.ts +++ b/webapp/src/app/api/model/keywordsRequest.ts @@ -1,24 +1,28 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ +import { FileUpload } from './fileUpload'; -export interface KeywordsRequest { - /** - * The input text from which to extract keywords. - */ - query: string; - /** - * The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'. - */ - mode: string; - /** - * The maximum number of keywords to extract. - */ - limit?: number; + +export interface KeywordsRequest { + /** + * The input text from which to extract keywords. + */ + query: string; + files?: Array | null; + /** + * The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'. + */ + mode: string; + /** + * The maximum number of keywords to extract. + */ + limit?: number; } + From b12e254caef8c761a21675f239e1d79741a5e729 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 11:36:30 +0200 Subject: [PATCH 24/60] added file upload component to keywords extraction UI --- .../keywords-search.component.html | 69 +++++--- .../keywords-search.component.scss | 4 +- .../keywords-search.component.ts | 151 +++++++++++++++--- 3 files changed, 185 insertions(+), 39 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 496e4154..8e50afb9 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -19,6 +19,7 @@ mat-flat-button type="button" class="extract-btn" + [disabled]="!form.controls.urlInput.value" [color]="isExtracting() ? 'warn' : 'primary'" (click)="onExtractKeywordsClick()"> @@ -43,6 +44,7 @@ + + + +
- - - text_fields - Extrahierte Keywords - - @if (topicMappingSearch()) { +
+ - account_tree - Topic Mapping + value="llm" + matTooltip="Extrahierte Keywords"> + text_fields + Extrahierte Keywords - } - + @if (topicMappingSearch()) { + + account_tree + Topic Mapping + + } + +
diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 2dac61de..5aa71fe2 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -19,10 +19,10 @@ $touch-target: 44px; .tab-content { display: flex; - flex-direction: column; margin-top: 0.5rem; gap: 0.5rem; - align-items: center; + align-items: top; + justify-content: center; } .full-width { diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 24286a8e..5987992e 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -32,6 +32,11 @@ import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { map } from 'rxjs/operators'; import { toSignal } from '@angular/core/rxjs-interop'; import { MatSliderModule } from '@angular/material/slider'; +import { FileUpload } from '../../api/model/fileUpload'; +import { + FileUploadComponent, + FileUploadItem, +} from '../../shared/ui/file-upload/file-upload.component'; import { MatButtonToggleModule, MatButtonToggleGroup, @@ -49,7 +54,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; import { DomSanitizer } from '@angular/platform-browser'; import { SearchResultsPayload } from './search-results/search-results-state.service'; -type InputMode = 'url' | 'text'; +type InputMode = 'url' | 'text' | 'file'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @Component({ @@ -77,6 +82,7 @@ type KeywordView = 'llm' | 'topic'; LoadingComponent, MatSlideToggleModule, MatSliderModule, + FileUploadComponent, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', @@ -89,19 +95,17 @@ export class KeywordsSearchComponent { private readonly destroyRef = inject(DestroyRef); private readonly websocketService = inject(KeywordWebSocketService); private readonly topicsService = inject(TopicsService); - + private readonly breakpointObserver = inject(BreakpointObserver); readonly form = this.formBuilder.nonNullable.group({ selectedInputType: 'url' as InputMode, urlInput: '', textInput: '', + fileInput: '', }); private readonly SESSION_KEY = 'keywords-search-source'; private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff'; - // in component class: - private breakpointObserver = inject(BreakpointObserver); - isMobile = toSignal( this.breakpointObserver .observe('(max-width: 768px)') @@ -127,6 +131,7 @@ export class KeywordsSearchComponent { readonly showVisualization = signal(false); readonly topicMappingSearch = signal(false); + readonly uploadedFiles = signal([]); readonly keywordsExist = computed( () => this.broadKeywords().length > 0 || @@ -180,10 +185,6 @@ export class KeywordsSearchComponent { } } } - console.log( - 'Highlighted content:', - this.sanitizer.bypassSecurityTrustHtml(highlightedContent), - ); return this.sanitizer.bypassSecurityTrustHtml(highlightedContent); }); @@ -356,14 +357,67 @@ export class KeywordsSearchComponent { // --- Tabs --------------------------------------------------------------- selectedTabIndex(): number { - return this.form.controls.selectedInputType.value === 'text' ? 1 : 0; + if (this.form.controls.selectedInputType.value === 'url') return 0; + if (this.form.controls.selectedInputType.value === 'text') return 1; + return 2; } onTabChange(index: number): void { - const nextMode: InputMode = index === 1 ? 'text' : 'url'; + let nextMode: InputMode; + if (index === 0) { + nextMode = 'url'; + } else if (index === 1) { + nextMode = 'text'; + } else { + nextMode = 'file'; + } this.form.controls.selectedInputType.setValue(nextMode); } + // fileupload + onFilesSelected(files: FileUploadItem[]): void { + this.uploadedFiles.set(files); + } + // Helper: Update progress bar + private updateProgress(processed: number, total: number) { + const progress = Math.round((processed / total) * 100); + this.progress.set(progress); + this.statusMessage.set(`Reading ${processed}/${total} files...`); + } + + // Helper: Send files to WebSocket for server-side extraction + private sendFilesToWebSocket(files: FileUpload[]) { + const keywordsRequest: KeywordsRequest = { + query: '', + files, + mode: 'files', + limit: undefined, + }; + + this.statusMessage.set('Files uploaded. Extracting keywords...'); + + this.websocketService + .sendRequest(keywordsRequest) + .then(() => { + this.statusMessage.set('Extracting keywords...'); + }) + .catch((err) => { + console.error('WebSocket error:', err); + this.statusMessage.set('Failed to send content'); + this.isExtracting.set(false); + }); + } + + onUploadProgress(event: { id: string; progress: number }) { + console.log('Upload progress:', event.progress + '%'); + this.progress.set(event.progress); + } + + onUploadError(error: { id: string; error: string }) { + console.error('Upload error:', error); + this.statusMessage.set('Upload failed: ' + error.error); + this.isExtracting.set(false); + } // --- Keyword selection & manual entry ------------------------------------ private keywordExists(keyword: string): boolean { @@ -539,6 +593,69 @@ export class KeywordsSearchComponent { this.cancelKeywordExtraction(); return; } + + const mode = this.form.controls.selectedInputType.value; + + if (mode === 'file') { + const files = this.uploadedFiles(); + if (!files || files.length === 0) { + this.statusMessage.set('Bitte Datei hochladen.'); + return; + } + + this.isExtracting.set(true); + this.progress.set(0); + this.statusMessage.set('Dateien werden verarbeitet...'); + + const totalFiles = files.length; + let processedFiles = 0; + const fileUploads: FileUpload[] = new Array(totalFiles); + + files.forEach((fileItem, index) => { + const file = fileItem.file; + const reader = new FileReader(); + + reader.onload = (e) => { + const dataUrl = e.target?.result as string; + const base64 = dataUrl.split(',')[1] ?? ''; + + fileUploads[index] = { + filename: file.name, + content_base64: base64, + mime_type: file.type || 'application/octet-stream', + }; + + processedFiles++; + this.updateProgress(processedFiles, totalFiles); + + if (processedFiles === totalFiles) { + this.sendFilesToWebSocket(fileUploads); + } + }; + + reader.onerror = () => { + console.error('Error reading file:', file.name); + fileUploads[index] = { + filename: file.name, + content_base64: '', + mime_type: file.type || 'application/octet-stream', + }; + + processedFiles++; + this.updateProgress(processedFiles, totalFiles); + + if (processedFiles === totalFiles) { + this.sendFilesToWebSocket(fileUploads); + } + }; + + reader.readAsDataURL(file); + }); + + return; + } + + // For URL and text, fall back to original behavior void this.extractKeywords(); } @@ -836,7 +953,6 @@ export class KeywordsSearchComponent { const legendExpanded = queryParams.get('legendExpanded') ?? 'off'; const softSearch = queryParams.get('softSearch') === 'true'; this.isRestoringState = true; - this.form.patchValue( { selectedInputType: mode, @@ -861,12 +977,6 @@ export class KeywordsSearchComponent { // enrich only newly added keywords that have no topic yet this.enrichManualKeywordsWithTopics(manual); - // User intent (the current selection): the URL is always authoritative - // here, deliberately overriding whatever the session cache had. This - // is what makes a deep link like ?selected=foo&manual=bar from another - // page reliably preselect keywords, instead of getting merged with (or - // hidden behind) leftover state from a previous visit in the same tab. - // clean up the selection to only include keywords that actually exist in const manualKeywordSet = new Set( this.getKeywordLabels(this.manualKeywords()).map((k) => @@ -1020,7 +1130,10 @@ export class KeywordsSearchComponent { } private parseMode(mode: string | null): InputMode { - return mode === 'text' ? 'text' : 'url'; + if (mode === 'url') return 'url'; + if (mode === 'text') return 'text'; + if (mode === 'file') return 'file'; + return 'url'; } private parseKeywordList(rawValue: string | null): string[] { From 233a2d2fca3103e807283cec433de4069382ad3d Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 11:37:12 +0200 Subject: [PATCH 25/60] file upload component added (version 1) --- .../ui/file-upload/file-upload.component.html | 88 ++++++ .../ui/file-upload/file-upload.component.scss | 145 +++++++++ .../ui/file-upload/file-upload.component.ts | 286 ++++++++++++++++++ 3 files changed, 519 insertions(+) create mode 100644 webapp/src/app/shared/ui/file-upload/file-upload.component.html create mode 100644 webapp/src/app/shared/ui/file-upload/file-upload.component.scss create mode 100644 webapp/src/app/shared/ui/file-upload/file-upload.component.ts diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.html b/webapp/src/app/shared/ui/file-upload/file-upload.component.html new file mode 100644 index 00000000..b44016cd --- /dev/null +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.html @@ -0,0 +1,88 @@ +
+ +
+ attach_file +

Drag & drop files here or click to browse

+ + Supported: {{ requiredFileType }} (Max: {{ maxFileSize / 1024 / 1024 }}MB, + {{ maxFiles }} files) + +
+ + + + + + @if (files.length > 0) { +
+ @for (file of files; track file.id) { + +
+
+ @if (file.file.type.startsWith('image/')) { + Preview + } @else { + {{ + getIcon(file.file.type) + }} + } +
+
+
{{ file.file.name }}
+
+ {{ (file.file.size / 1024 / 1024).toFixed(2) }} MB +
+
+
+ + + @if (file.progress > 0) { +
+ + {{ file.progress }}% +
+ } + + +
+ + + +
+
+ } +
+ } +
diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.scss b/webapp/src/app/shared/ui/file-upload/file-upload.component.scss new file mode 100644 index 00000000..8ad94b72 --- /dev/null +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.scss @@ -0,0 +1,145 @@ +.file-upload-container { + width: 100%; + max-width: 600px; + margin: 0 auto; +} + +.drop-zone { + border: 2px dashed #ccc; + border-radius: 12px; + padding: 40px 20px; + text-align: center; + cursor: pointer; + transition: all 0.3s ease; + background-color: #f9f9f9; + + .upload-icon { + font-size: 48px; + color: #1976d2; + margin-bottom: 12px; + } + + .drop-text { + font-size: 16px; + color: #555; + margin-bottom: 8px; + } + + .file-info { + font-size: 12px; + color: #888; + } + + &.drag-over { + border-color: #1976d2; + background-color: #e3f2fd; + } +} + +.file-list { + margin-top: 16px; +} + +.file-card { + margin-bottom: 12px; + border-radius: 8px; + overflow: hidden; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + + .file-header { + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background-color: #f5f5f5; + } + + .file-preview { + width: 50px; + height: 50px; + border-radius: 8px; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + background-color: #ddd; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } + + .file-icon { + font-size: 32px; + color: #666; + } + + mat-icon { + font-size: 32px; + color: #666; + } + } + + .file-info { + flex: 1; + font-size: 14px; + + .file-name { + font-weight: 500; + color: #333; + } + + .file-size { + font-size: 12px; + color: #888; + } + } + + .progress-container { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background-color: #e8f5e9; + + .progress-bar { + flex: 1; + } + + .progress-text { + font-size: 12px; + color: #2e7d32; + } + } + + .file-actions { + display: flex; + gap: 4px; + padding: 8px 12px; + background-color: #f0f0f0; + + button { + padding: 4px; + } + } +} + +/* Responsive */ +@media (max-width: 600px) { + .drop-zone { + padding: 30px 16px; + } + + .file-card { + .file-header { + flex-direction: column; + text-align: center; + } + + .file-preview { + width: 60px; + height: 60px; + } + } +} diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.ts b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts new file mode 100644 index 00000000..40b52830 --- /dev/null +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts @@ -0,0 +1,286 @@ +import { + Component, + Input, + Output, + EventEmitter, + ViewChild, + ElementRef, + OnDestroy, + OnInit, +} from '@angular/core'; +import { HttpClient, HttpEventType } from '@angular/common/http'; +import { Subscription } from 'rxjs'; +import { finalize } from 'rxjs/operators'; + +import { MatCardModule } from '@angular/material/card'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatDividerModule } from '@angular/material/divider'; + +export interface FileUploadItem { + file: File; + previewUrl?: string; + progress: number; + error?: string; + id: string; +} + +@Component({ + selector: 'app-file-upload', + imports: [ + MatCardModule, + MatProgressBarModule, + MatIconModule, + MatTooltipModule, + MatChipsModule, + MatDividerModule, + ], + templateUrl: 'file-upload.component.html', + styleUrls: ['file-upload.component.scss'], +}) +export class FileUploadComponent implements OnInit, OnDestroy { + @Input() + uploadUrl: string = ''; + + @Input() + requiredFileType: string | string[] = 'application/pdf'; + + @Input() + maxFileSize: number = 10 * 1024 * 1024; // 10MB + + @Input() + maxFiles: number = 5; + + @Input() + autoUpload: boolean = false; + + @Output() + filesSelected = new EventEmitter(); + + @Output() + uploadProgressChange = new EventEmitter<{ id: string; progress: number }>(); + + @Output() + uploadComplete = new EventEmitter(); + + @Output() + uploadError = new EventEmitter<{ id: string; error: string }>(); + + @ViewChild('fileInput', { static: true }) + fileInput!: ElementRef; + + @ViewChild('dropZone', { static: true }) + dropZone!: ElementRef; + + files: FileUploadItem[] = []; + uploadSub: Subscription = Subscription.EMPTY; + + isDragging = false; + + constructor(private http: HttpClient) {} + + ngOnInit() { + this.setupDragAndDrop(); + } + + ngOnDestroy() { + if (this.uploadSub) { + this.uploadSub.unsubscribe(); + } + } + + private setupDragAndDrop() { + const zone = this.dropZone.nativeElement; + + zone.addEventListener('dragover', (e) => { + e.preventDefault(); + this.isDragging = true; + }); + + zone.addEventListener('dragleave', () => { + this.isDragging = false; + }); + + zone.addEventListener('drop', (e) => { + e.preventDefault(); + this.isDragging = false; + const files = e.dataTransfer?.files; + if (files) { + this.handleFiles(files); + } + }); + } + + onFileChange(event: Event) { + const input = event.target as HTMLInputElement; + if (input.files) { + this.handleFiles(input.files); + } + } + + private handleFiles(files: FileList) { + if (this.files.length + 1 > this.maxFiles) { + this.uploadError.emit({ + id: this.generateId(), + error: `Maximum ${this.maxFiles} files allowed`, + }); + return; + } + const fileArray = Array.from(files); + const validFiles: File[] = []; + + fileArray.forEach((file) => { + if (!this.isValidFile(file)) { + return; + } + validFiles.push(file); + }); + + if (validFiles.length === 0) return; + + const newFiles = validFiles.map((file) => ({ + file, + id: this.generateId(), + progress: 0, + previewUrl: this.getPreviewUrl(file), + })); + + this.files = [...this.files, ...newFiles]; + + this.filesSelected.emit(this.files); + + if (this.autoUpload) { + this.uploadAll(); + } + } + + private isValidFile(file: File): boolean { + const type = file.type; + const size = file.size; + + const allowedTypes = Array.isArray(this.requiredFileType) + ? this.requiredFileType + : this.requiredFileType.split(','); + + const isValidType = allowedTypes.some((t) => { + if (t.includes('/')) return type.startsWith(t); + if (t === 'image') return type.startsWith('image/'); + if (t === 'pdf') return type === 'application/pdf'; + if (t === 'text') return type.startsWith('text/'); + return false; + }); + + if (!isValidType) { + this.uploadError.emit({ + id: this.generateId(), + error: `File type not allowed: ${file.name}`, + }); + return false; + } + + if (size > this.maxFileSize) { + this.uploadError.emit({ + id: this.generateId(), + error: `File too large: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`, + }); + return false; + } + + if (this.files.length + 1 > this.maxFiles) { + this.uploadError.emit({ + id: this.generateId(), + error: `Maximum ${this.maxFiles} files allowed`, + }); + return false; + } + + return true; + } + + private getPreviewUrl(file: File): string | undefined { + const type = file.type; + if (type.startsWith('image/')) { + return URL.createObjectURL(file); + } + return undefined; + } + + private generateId(): string { + return Math.random().toString(36).substr(2, 9); + } + + getIcon(fileType: string): string { + if (fileType.startsWith('image/')) { + return 'image'; + } + if (fileType === 'application/pdf') { + return 'picture_as_pdf'; + } + if (fileType.startsWith('text/')) { + return 'description'; + } + return 'insert_drive_file'; + } + + uploadAll() { + if (!this.uploadUrl) { + console.error('Upload URL is required!'); + return; + } + + this.uploadSub = this.http + .post( + this.uploadUrl, + this.files.map((f) => f.file), + { + reportProgress: true, + observe: 'events', + }, + ) + .pipe(finalize(() => this.reset())) + .subscribe((event) => { + if (event.type === HttpEventType.UploadProgress) { + const index = Math.floor((event.loaded / event.total!) * 100); + const id = this.files[0]?.id; + if (id) { + this.files = this.files.map((f) => ({ + ...f, + progress: index, + })); + this.uploadProgressChange.emit({ id, progress: index }); + } + } + }); + } + + cancelUpload(id: string) { + const file = this.files.find((f) => f.id === id); + if (file) { + this.files = this.files.filter((f) => f.id !== id); + this.uploadError.emit({ id, error: 'Upload cancelled' }); + } + } + + reset() { + this.uploadSub.unsubscribe(); + this.uploadSub = Subscription.EMPTY; + } + + removeFile(id: string) { + this.files = this.files.filter((f) => f.id !== id); + } + + downloadFile(id: string) { + const file = this.files.find((f) => f.id === id); + if (file) { + const url = URL.createObjectURL(file.file); + const a = document.createElement('a'); + a.href = url; + a.download = file.file.name; + a.click(); + URL.revokeObjectURL(url); + } + } +} From 23b1be3b7bbf5b8e931b7f9c6394e6be4e4e78f5 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 9 Jul 2026 15:01:43 +0200 Subject: [PATCH 26/60] Add patents-by-keywords mapping pipeline and keyword patent search flow --- .../build_patents_openalex_keywords.py | 143 ++++ service/scripts/diagnose_keyword_patents.py | 91 +++ .../diagnose_patents_openalex_keywords.py | 89 ++ .../main/inse/patents/keywords/__init__.py | 0 .../src/main/inse/patents/keywords/logic.py | 405 ++++++++++ .../src/main/inse/patents/keywords/model.py | 46 ++ .../inse/patents/keywords/reverse_lookup.py | 760 ++++++++++++++++++ .../inse/patents/keywords/search_queries.py | 166 ++++ .../src/main/inse/patents/keywords/service.py | 23 + .../main/inse/patents/keywords/test_logic.py | 128 +++ .../patents_openalex_keywords/__init__.py | 0 .../patents_openalex_keywords/client.py | 171 ++++ .../patents_openalex_keywords/ipc_entries.py | 207 +++++ .../patents_openalex_keywords/mapping.py | 34 + .../patents_openalex_keywords/matching.py | 409 ++++++++++ .../patents_openalex_keywords/resolver.py | 284 +++++++ .../test_matching.py | 88 ++ .../test_resolver.py | 102 +++ webapp/src/app/api/api/patents.service.ts | 19 + .../api/model/patentsByKeywordsResponse.ts | 26 + .../keywords-patents.component.html | 114 +++ .../keywords-patents.component.scss | 145 ++++ .../keywords-patents.component.ts | 88 ++ .../keywords-search.component.html | 22 +- .../keywords-search.component.scss | 15 +- .../keywords-search.component.ts | 84 +- 26 files changed, 3643 insertions(+), 16 deletions(-) create mode 100644 service/scripts/build_patents_openalex_keywords.py create mode 100644 service/scripts/diagnose_keyword_patents.py create mode 100644 service/scripts/diagnose_patents_openalex_keywords.py create mode 100644 service/src/main/inse/patents/keywords/__init__.py create mode 100644 service/src/main/inse/patents/keywords/logic.py create mode 100644 service/src/main/inse/patents/keywords/model.py create mode 100644 service/src/main/inse/patents/keywords/reverse_lookup.py create mode 100644 service/src/main/inse/patents/keywords/search_queries.py create mode 100644 service/src/main/inse/patents/keywords/service.py create mode 100644 service/src/main/inse/patents/keywords/test_logic.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/__init__.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/client.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/mapping.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/matching.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/resolver.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_matching.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py create mode 100644 webapp/src/app/api/model/patentsByKeywordsResponse.ts create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts diff --git a/service/scripts/build_patents_openalex_keywords.py b/service/scripts/build_patents_openalex_keywords.py new file mode 100644 index 00000000..606660a3 --- /dev/null +++ b/service/scripts/build_patents_openalex_keywords.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +""" +build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches. + +Fetches IPC/CPC metadata from the `ipc` index, matches labels against OpenAlex topics +(from topic_hierarchy_cache.json) and keywords (from openalex-topics) using +SentenceTransformer embeddings, then writes results to the patents_openalex_keywords +Elasticsearch index and a local JSON backup. + +Usage: + python scripts/build_patents_openalex_keywords.py + python scripts/build_patents_openalex_keywords.py --top-k 3 --min-score 0.55 + python scripts/build_patents_openalex_keywords.py --levels section class subclass + python scripts/build_patents_openalex_keywords.py --skip-keywords + +Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials (INSE) and, unless +--skip-keywords is set, NES Elasticsearch credentials for openalex-topics. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import ( + DEFAULT_BUILD_LEVELS, + fetch_unique_ipc_entries, +) +from inse.patents.patents_openalex_keywords.matching import ( + TopicVectorsMatcher, + build_documents_from_topicvectors, + documents_to_json_mapping, +) + +logger = logging.getLogger(__name__) + + +async def run(args: argparse.Namespace) -> None: + levels = tuple(args.levels) + + ipc_entries = await fetch_unique_ipc_entries(levels=levels) + counts = {level: len(ipc_entries.get(level, {})) for level in levels} + logger.info("Fetched unique IPC/CPC symbols: %s", counts) + + if args.skip_keywords: + logger.info("--skip-keywords is ignored in topicvectors mode") + if args.topic_cache: + logger.info("--topic-cache is ignored in topicvectors mode") + if args.batch_size != 64: + logger.info("--batch-size is ignored in topicvectors mode") + + matcher = TopicVectorsMatcher(min_score=args.min_score) + logger.info("Matching IPC/CPC labels against topicvectors index...") + documents = await build_documents_from_topicvectors( + ipc_entries, matcher, levels=levels, top_k=args.top_k + ) + logger.info("Built %d IPC/CPC mapping documents", len(documents)) + + if args.output: + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + mapping = documents_to_json_mapping(documents) + output_path.write_text( + json.dumps(mapping, indent=2, ensure_ascii=True), + encoding="utf-8", + ) + logger.info("Wrote local JSON backup to %s", output_path) + + if not args.dry_run: + client = PatentsOpenAlexKeywordsClient(timeout=60.0) + await client.ensure_index() + await client.bulk_index(documents) + logger.info("Indexed %d documents into patents_openalex_keywords", len(documents)) + else: + logger.info("Dry run — skipped Elasticsearch indexing") + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Build IPC/CPC → OpenAlex topic/keyword matches with SentenceTransformer.", + ) + parser.add_argument( + "--output", + default=str( + current_dir.parent / "src" / "data" / "patents_openalex_keywords_mapping.json" + ), + help="Local JSON backup path", + ) + parser.add_argument( + "--topic-cache", + default=None, + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--levels", + nargs="+", + default=list(DEFAULT_BUILD_LEVELS), + choices=list(DEFAULT_BUILD_LEVELS), + help="IPC/CPC hierarchy levels to map", + ) + parser.add_argument( + "--top-k", + type=int, + default=3, + help="Number of top topic/keyword matches per IPC/CPC code", + ) + parser.add_argument( + "--min-score", + type=float, + default=0.5, + help="Minimum cosine similarity for a match", + ) + parser.add_argument( + "--batch-size", + type=int, + default=64, + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--skip-keywords", + action="store_true", + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Build matches locally without indexing into Elasticsearch", + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + asyncio.run(run(args)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/diagnose_keyword_patents.py b/service/scripts/diagnose_keyword_patents.py new file mode 100644 index 00000000..7beeeb44 --- /dev/null +++ b/service/scripts/diagnose_keyword_patents.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Diagnose keyword → patent search for a given keyword.""" +from __future__ import annotations + +import argparse +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from dotenv import load_dotenv + +load_dotenv(current_dir.parent / "src" / "main" / "inse" / ".env") + +from inse.patents.authors.ipc_openalex_mapping import _load_topic_cache +from inse.patents.keywords.logic import _patent_search_terms, get_patents_by_keywords +from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest +from inse.patents.keywords.reverse_lookup import KeywordIpcReverseLookup + + +def _find_topic(keyword: str) -> tuple[str, dict]: + cache = _load_topic_cache() + keyword_lower = keyword.casefold() + for name, info in cache.items(): + if keyword_lower in name.casefold(): + return name, info + for name, info in cache.items(): + if info.get("subfield", "").casefold() == keyword_lower: + return name, info + return keyword, {} + + +async def diagnose(keyword: str, topic_name: str | None, topic_id: str | None) -> None: + if topic_name and topic_id: + display_name = topic_name + tid = topic_id + info = _load_topic_cache().get(topic_name, {}) + else: + display_name, info = _find_topic(keyword) + tid = info.get("topic_id") + + item = KeywordPatentSearchItem( + keyword=keyword, + topic_id=tid, + topic_display_name=display_name, + subfield_name=info.get("subfield"), + field_name=info.get("field"), + relevance_score=1.0, + ) + print(f"Keyword: {keyword}") + print(f"Topic: {display_name} ({tid})") + print(f"Subfield: {info.get('subfield')} | Field: {info.get('field')}") + + lookup = KeywordIpcReverseLookup() + ipc = await lookup.lookup_ipc_codes([item]) + print(f"\nIPC matches ({len(ipc)}):") + for match in ipc[:20]: + print( + f" {match.ipc_symbol:14} score={match.match_score:.3f} " + f"type={match.match_type}" + ) + + terms = _patent_search_terms(ipc) + print(f"\nPatent search terms ({len(terms)}): {terms}") + + response = await get_patents_by_keywords(PatentsByKeywordsRequest(keywords=[item])) + print(f"\nPatents returned: {response.patent_count}") + for entry in response.patents[:10]: + patent = entry.patent + title = (patent.title or "")[:60] + print( + f" score={entry.match_score:.3f} {patent.patent_id} " + f"ipc={entry.matched_ipc_symbols} | {title}" + ) + if patent.ipc: + print(f" raw ipc: {patent.ipc[:2]}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("keyword", default="Medizin", nargs="?") + parser.add_argument("--topic-name", default=None) + parser.add_argument("--topic-id", default=None) + args = parser.parse_args() + asyncio.run(diagnose(args.keyword, args.topic_name, args.topic_id)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/diagnose_patents_openalex_keywords.py b/service/scripts/diagnose_patents_openalex_keywords.py new file mode 100644 index 00000000..d226739f --- /dev/null +++ b/service/scripts/diagnose_patents_openalex_keywords.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Print IPC/CPC → OpenAlex topic/keyword matches from patents_openalex_keywords.""" +from __future__ import annotations + +import argparse +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +DEFAULT_SYMBOLS = ("A", "A61", "A61B", "G01N", "C12N", "H04L") + + +def _print_match_block(title: str, matches: list[dict]) -> None: + print(f" {title}:") + if not matches: + print(" (none)") + return + for item in matches: + if "keyword" in item: + label = item.get("keyword") + topic = item.get("topic_display_name") or item.get("topic_id") + print( + f" #{item.get('rank')} {label} " + f"[topic={topic}, score={item.get('match_score')}]" + ) + else: + label = item.get("topic_display_name") or item.get("topic_id") + print(f" #{item.get('rank')} {label} (score={item.get('match_score')})") + + +async def diagnose_symbol(client: PatentsOpenAlexKeywordsClient, symbol: str) -> None: + normalized = normalize_symbol(symbol) + print(f"\n{'=' * 70}") + print(f"IPC/CPC symbol: {normalized}") + + doc = await client.lookup_symbol(normalized) + if doc: + print(f"Matched level: {doc.get('ipc_level')}") + print(f"IPC label: {doc.get('ipc_label')}") + _print_match_block("Topic matches", doc.get("topic_matches") or []) + _print_match_block("Keyword matches", doc.get("keyword_matches") or []) + return + + subclass = infer_subclass(normalized) + for level, candidate in ( + ("subgroup", normalized), + ("group", normalized), + ("subclass", subclass), + ("class", normalized[:3] if len(normalized) >= 3 else None), + ("section", normalized[:1] if normalized else None), + ): + if not candidate: + continue + doc = await client.lookup(level, candidate) + if doc: + print(f"Matched level: {doc.get('ipc_level')} (via fallback lookup)") + print(f"IPC label: {doc.get('ipc_label')}") + _print_match_block("Topic matches", doc.get("topic_matches") or []) + _print_match_block("Keyword matches", doc.get("keyword_matches") or []) + return + + print(" No mapping found in patents_openalex_keywords.") + + +async def main() -> None: + parser = argparse.ArgumentParser( + description="Diagnose IPC/CPC matches in patents_openalex_keywords.", + ) + parser.add_argument( + "symbols", + nargs="*", + default=list(DEFAULT_SYMBOLS), + help="IPC/CPC symbols to inspect", + ) + args = parser.parse_args() + + client = PatentsOpenAlexKeywordsClient() + for symbol in args.symbols: + await diagnose_symbol(client, symbol) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/src/main/inse/patents/keywords/__init__.py b/service/src/main/inse/patents/keywords/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py new file mode 100644 index 00000000..6daeabe4 --- /dev/null +++ b/service/src/main/inse/patents/keywords/logic.py @@ -0,0 +1,405 @@ +"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index.""" +from __future__ import annotations + +import asyncio +import logging + +import httpx + +from inse.patents.common import model +from inse.patents.common.elastic_search_client import ( + BasePatentSearchClient, + MissingApiKeyError, +) +from inse.patents.common.parsing import ( + deduplicate_patents, + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, +) +from inse.patents.ipc_lookup import extract_ipc_symbol +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.keywords.model import ( + KeywordPatentMatch, + KeywordPatentSearchItem, + PatentsByKeywordsRequest, + PatentsByKeywordsResponse, +) +from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup +from inse.patents.keywords.search_queries import ( + IpcPatentSearchQueries, + _search_terms_for_symbol, +) +from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol + +logger = logging.getLogger(__name__) + +_MAX_PATENTS = 100 +_MAX_IPC_CODES = 40 +_MAX_PATENT_SEARCH_TERMS = 12 +_MIN_IPC_MATCH_SCORE = 0.45 +_MIN_PATENT_MATCH_SCORE = 0.35 + + +def _ipc_section(symbol: str) -> str: + normalized = normalize_symbol(symbol) + return normalized[:1] if normalized else "" + + +def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> set[str]: + weights: dict[str, float] = {} + for match in ipc_matches: + section = _ipc_section(match.ipc_symbol) + if not section: + continue + weights[section] = weights.get(section, 0.0) + match.match_score + ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True) + return {section for section, _ in ranked[:limit]} + + +def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: + if not ipc_matches: + return [] + + ranked = sorted(ipc_matches, key=lambda match: match.match_score, reverse=True) + strong = [ + match + for match in ranked + if match.match_score >= _MIN_IPC_MATCH_SCORE or match.match_type == "heuristic" + ] + if not strong: + strong = ranked[:8] + + dominant_sections = _dominant_ipc_sections(strong) + filtered: list[IpcCodeMatch] = [] + seen: set[tuple[str, str]] = set() + for match in strong: + key = (match.ipc_level, match.ipc_symbol) + if key in seen: + continue + if match.match_type == "heuristic": + filtered.append(match) + seen.add(key) + continue + if match.match_score >= 0.8: + filtered.append(match) + seen.add(key) + continue + if _ipc_section(match.ipc_symbol) in dominant_sections: + filtered.append(match) + seen.add(key) + + return filtered or strong[:12] + + +def _active_heuristic_prefixes(ipc_matches: list[IpcCodeMatch]) -> set[str]: + prefixes: set[str] = set() + for match in ipc_matches: + if match.match_type != "heuristic": + continue + symbol = normalize_symbol(match.ipc_symbol) + if not symbol: + continue + for prefix in ( + "A61", + "B01", + "C01", + "C07", + "C08", + "C09", + "C10", + "C12", + "G01N", + "G06", + "B60", + "F02", + ): + if symbol.startswith(prefix): + prefixes.add(prefix) + return prefixes + + +def _symbol_matches_heuristic_prefixes(symbol: str, prefixes: set[str]) -> bool: + normalized = normalize_symbol(symbol) + return any(normalized.startswith(prefix) for prefix in prefixes) + + +def _ipc_search_domain(symbol: str) -> str: + normalized = normalize_symbol(symbol) + if normalized.startswith("A61"): + return "medicine" + if ( + normalized.startswith("C") + or normalized.startswith("B01") + or normalized.startswith("G01N") + ): + return "chemistry" + if normalized.startswith("B60") or normalized.startswith("F02"): + return "automotive" + if normalized.startswith("G06"): + return "cs_ai" + return "other" + + +def _term_from_ipc_match(match: IpcCodeMatch) -> str | None: + from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass + + return infer_subclass(normalize_symbol(match.ipc_symbol)) + + +def _interleave_ipc_matches( + matches: list[IpcCodeMatch], + *, + limit: int, +) -> list[IpcCodeMatch]: + from collections import defaultdict + + by_domain: dict[str, list[IpcCodeMatch]] = defaultdict(list) + for match in matches: + by_domain[_ipc_search_domain(match.ipc_symbol)].append(match) + + if len(by_domain) <= 1: + return matches[:limit] + + ordered: list[IpcCodeMatch] = [] + seen: set[tuple[str, str]] = set() + queues = list(by_domain.values()) + while len(ordered) < limit and queues: + progressed = False + for queue in list(queues): + if len(ordered) >= limit: + break + while queue: + match = queue.pop(0) + key = (match.ipc_level, match.ipc_symbol) + if key in seen: + continue + seen.add(key) + ordered.append(match) + progressed = True + break + queues = [queue for queue in queues if queue] + if not progressed: + break + return ordered + + +def _balanced_patent_matches( + scored: list[KeywordPatentMatch], + limit: int, +) -> list[KeywordPatentMatch]: + from collections import defaultdict + + by_domain: dict[str, list[KeywordPatentMatch]] = defaultdict(list) + for item in scored: + domain = ( + _ipc_search_domain(item.matched_ipc_symbols[0]) + if item.matched_ipc_symbols + else "other" + ) + by_domain[domain].append(item) + + if len(by_domain) <= 1: + return scored[:limit] + + ordered: list[KeywordPatentMatch] = [] + seen_ids: set[str] = set() + queues = list(by_domain.values()) + while len(ordered) < limit and queues: + progressed = False + for queue in list(queues): + if len(ordered) >= limit: + break + while queue: + item = queue.pop(0) + if item.patent.patent_id in seen_ids: + continue + seen_ids.add(item.patent.patent_id) + ordered.append(item) + progressed = True + break + queues = [queue for queue in queues if queue] + if not progressed: + break + return ordered + + +def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]: + filtered = _filter_ipc_matches_for_search(ipc_matches) + active_prefixes = _active_heuristic_prefixes(ipc_matches) + if active_prefixes: + filtered = [ + match + for match in filtered + if _symbol_matches_heuristic_prefixes(match.ipc_symbol, active_prefixes) + ] + + filtered = _interleave_ipc_matches(filtered, limit=_MAX_PATENT_SEARCH_TERMS) + terms: list[str] = [] + seen: set[str] = set() + for match in filtered: + subclass = _term_from_ipc_match(match) + if not subclass or subclass in seen: + continue + seen.add(subclass) + terms.append(subclass) + if len(terms) >= _MAX_PATENT_SEARCH_TERMS: + break + return terms + + +def _ipc_terms_overlap(patent_code: str, mapped_symbol: str) -> bool: + patent_terms = set( + _search_terms_for_symbol(extract_ipc_symbol(patent_code) or patent_code) + ) + mapped_terms = set(_search_terms_for_symbol(mapped_symbol)) + return bool(patent_terms & mapped_terms) + + +def _patent_code_matches_symbol(patent_code: str, mapped_symbol: str) -> bool: + if _ipc_terms_overlap(patent_code, mapped_symbol): + return True + normalized_patent = normalize_symbol(extract_ipc_symbol(patent_code)) + normalized_mapped = normalize_symbol(mapped_symbol) + if not normalized_patent or not normalized_mapped: + return False + return ( + normalized_patent.startswith(normalized_mapped) + or normalized_mapped.startswith(normalized_patent) + ) + + +def _score_patent( + patent: model.PatentEntry, + ipc_matches: list[IpcCodeMatch], +) -> tuple[float, list[str], list[str]] | None: + best_score = 0.0 + matched_keywords: set[str] = set() + matched_symbols: set[str] = set() + + patent_codes = [ + normalize_symbol(extract_ipc_symbol(code)) + for code in (*patent.ipc, *patent.cpc) + if extract_ipc_symbol(code) + ] + + for ipc_match in ipc_matches: + for patent_code in patent_codes: + if _patent_code_matches_symbol(patent_code, ipc_match.ipc_symbol): + if ipc_match.match_score > best_score: + best_score = ipc_match.match_score + matched_keywords.add(ipc_match.source_keyword) + matched_symbols.add(ipc_match.ipc_symbol) + + if best_score <= 0: + return None + + return ( + best_score, + sorted(matched_keywords), + sorted(matched_symbols), + ) + + +async def get_patents_by_keywords( + request: PatentsByKeywordsRequest, + *, + reverse_lookup: KeywordIpcReverseLookup | None = None, + search_client: BasePatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, +) -> PatentsByKeywordsResponse: + lookup = reverse_lookup or KeywordIpcReverseLookup() + client = search_client or BasePatentSearchClient() + ipc_search = ipc_client or IpcSearchClient() + queries = IpcPatentSearchQueries() + + ipc_matches = await lookup.lookup_ipc_codes( + request.keywords, + max_codes=_MAX_IPC_CODES, + ) + ipc_matches = _filter_ipc_matches_for_search(ipc_matches) + if not ipc_matches: + logger.info( + "Keyword patent search: no IPC codes for keywords %s", + [item.keyword for item in request.keywords], + ) + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + + symbols = _patent_search_terms(ipc_matches) + if not symbols: + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + + try: + epo_data, uspto_data = await asyncio.gather( + client.search_epo(queries.epo_query_by_ipc_terms(symbols, size=_MAX_PATENTS)), + client.search_uspto( + queries.uspto_query_by_ipc_terms(symbols, size=_MAX_PATENTS) + ), + ) + except MissingApiKeyError: + logger.warning("Patent search skipped: Elasticsearch API key not configured.") + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + except httpx.HTTPError as exc: + logger.warning("Patent search failed: %s", exc) + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + + raw_patents = deduplicate_patents( + parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + ) + + scored: list[KeywordPatentMatch] = [] + for patent in raw_patents: + result = _score_patent(patent, ipc_matches) + if result is None: + continue + score, matched_keywords, matched_symbols = result + if score < _MIN_PATENT_MATCH_SCORE: + continue + scored.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + matched_keywords=matched_keywords, + matched_ipc_symbols=matched_symbols, + ) + ) + + scored.sort( + key=lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ), + reverse=True, + ) + scored = _balanced_patent_matches(scored, _MAX_PATENTS) + + patents = [item.patent for item in scored] + await enrich_patents_classifications(patents, ipc_search) + + return PatentsByKeywordsResponse( + patent_count=len(scored), + patents=scored, + ) + + +def keyword_items_from_entries( + entries: list[dict], +) -> list[KeywordPatentSearchItem]: + """Helper for tests – build search items from serialized keyword entries.""" + items: list[KeywordPatentSearchItem] = [] + for entry in entries: + llm = entry.get("llm_keyword") or {} + topic_mapping = entry.get("topic_mapping") or {} + topic = topic_mapping.get("topic") or {} + items.append( + KeywordPatentSearchItem( + keyword=str(llm.get("keyword") or "").strip(), + topic_id=topic.get("id"), + topic_display_name=topic.get("display_name"), + subfield_name=(topic.get("subfield") or {}).get("display_name"), + field_name=(topic.get("field") or {}).get("display_name"), + relevance_score=float(llm.get("relevance_score") or 1.0), + ) + ) + return [item for item in items if item.keyword] diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py new file mode 100644 index 00000000..0c435b1c --- /dev/null +++ b/service/src/main/inse/patents/keywords/model.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel, Field + +from inse.patents.common.model import PatentEntry + + +class KeywordPatentSearchItem(BaseModel): + keyword: str = Field(description="Extracted keyword text.") + topic_id: str | None = Field( + default=None, + description="OpenAlex topic id from keyword enrichment, if available.", + ) + topic_display_name: str | None = Field( + default=None, + description="OpenAlex topic display name from enrichment, if available.", + ) + subfield_name: str | None = Field( + default=None, + description="OpenAlex subfield name from enrichment, if available.", + ) + field_name: str | None = Field( + default=None, + description="OpenAlex field name from enrichment, if available.", + ) + relevance_score: float = Field( + default=1.0, + description="LLM relevance score for the keyword.", + ) + + +class PatentsByKeywordsRequest(BaseModel): + keywords: list[KeywordPatentSearchItem] = Field( + min_length=1, + description="Keywords to match against patents_openalex_keywords.", + ) + + +class KeywordPatentMatch(BaseModel): + patent: PatentEntry + match_score: float = Field(description="Combined match quality score.") + matched_keywords: list[str] = Field(default_factory=list) + matched_ipc_symbols: list[str] = Field(default_factory=list) + + +class PatentsByKeywordsResponse(BaseModel): + patent_count: int + patents: list[KeywordPatentMatch] diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py new file mode 100644 index 00000000..13b9e097 --- /dev/null +++ b/service/src/main/inse/patents/keywords/reverse_lookup.py @@ -0,0 +1,760 @@ +"""Reverse lookup: OpenAlex keywords/topics → IPC/CPC codes via patents_openalex_keywords.""" +from __future__ import annotations + +import logging +from dataclasses import dataclass +from functools import lru_cache +from typing import Any + +import httpx + +from inse.patents.authors.ipc_openalex_mapping import ( + _load_topic_cache, + load_ipc_openalex_mapping, + normalize_openalex_id, +) +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.keywords.model import KeywordPatentSearchItem +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol +from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX +from inse.patents.patents_openalex_keywords.resolver import load_patents_openalex_keywords_json + +logger = logging.getLogger(__name__) + +_CS_AI_IPC_SUBCLASSES = ("G06N", "G06F", "G06T", "G06V", "G06K", "G06Q") +_AUTOMOTIVE_IPC_SUBCLASSES = ( + "B60L", + "B60K", + "B60W", + "B60R", + "B60H", + "B60Q", + "B60M", + "F02M", + "F02D", +) +_MEDICINE_IPC_SUBCLASSES = ("A61B", "A61K", "A61M", "A61P", "A61N", "A61F") +_CHEMISTRY_IPC_SUBCLASSES_GENERAL = ("C07C", "C01B", "C08L", "G01N") +_CHEMISTRY_IPC_SUBCLASSES_ORGANIC = ("C07C", "C07D") +_CHEMISTRY_IPC_SUBCLASSES_INORGANIC = ("C01B", "C01G") +_CHEMISTRY_IPC_SUBCLASSES_POLYMER = ("C08L", "C08G") +_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM = ("C12N", "C12Q") +_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL = ("G01N",) +_CHEMISTRY_IPC_SUBCLASSES_PROCESS = ("B01J", "B01D") +_CHEMISTRY_RELATED_SUBFIELDS = frozenset( + { + "organic chemistry", + "inorganic chemistry", + "physical and theoretical chemistry", + "analytical chemistry", + "materials chemistry", + "environmental chemistry", + "biochemistry", + "process chemistry and technology", + "spectroscopy", + "clinical biochemistry", + "geochemistry and petrology", + "pharmaceutical science", + } +) +_CHEMISTRY_RELATED_FIELDS = frozenset( + { + "chemistry", + "chemical engineering", + } +) +_MEDICINE_RELATED_SUBFIELDS = frozenset( + { + "medicine", + "public health", + "health professions", + "pharmacology", + "surgery", + "oncology", + "radiology, nuclear medicine and imaging", + "cardiology and cardiovascular medicine", + "epidemiology", + "immunology", + } +) +_MEDICINE_RELATED_FIELDS = frozenset( + { + "medicine", + "health professions", + "nursing", + "pharmacology, toxicology and pharmaceutics", + "biochemistry, genetics and molecular biology", + } +) +_AI_RELATED_SUBFIELDS = frozenset( + { + "artificial intelligence", + "computer vision and pattern recognition", + "signal processing", + "information systems and management", + "human-computer interaction", + "software", + } +) + +_LEVEL_WEIGHTS = { + "subgroup": 1.0, + "group": 0.92, + "subclass": 0.85, + "class": 0.75, + "section": 0.6, +} + + +@dataclass(frozen=True) +class IpcCodeMatch: + ipc_level: str + ipc_symbol: str + match_score: float + source_keyword: str + match_type: str + + +def _keyword_variants(keyword: str) -> list[str]: + normalized = keyword.strip().casefold() + if not normalized: + return [] + return list(dict.fromkeys([normalized, keyword.strip()])) + + +def _topic_id_variants(topic_id: str | None) -> list[str]: + if not topic_id or not str(topic_id).strip(): + return [] + raw = str(topic_id).strip() + short = normalize_openalex_id(raw) + variants = [raw] + if short: + variants.append(short) + variants.append(f"https://openalex.org/{short}") + return list(dict.fromkeys(variants)) + + +def _weighted_score( + ipc_level: str, + base_score: float, + relevance_score: float, +) -> float: + level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7) + relevance = max(relevance_score, 0.1) + return round(base_score * level_weight * relevance, 4) + + +@lru_cache(maxsize=1) +def _build_json_inverted_index() -> tuple[ + dict[str, list[tuple[str, str, float, str, str]]], + dict[str, list[tuple[str, str, float, str, str]]], +]: + """keyword/topic_id -> list of (level, symbol, score, source_keyword, match_type).""" + by_keyword: dict[str, list[tuple[str, str, float, str, str]]] = {} + by_topic: dict[str, list[tuple[str, str, float, str, str]]] = {} + + table = load_patents_openalex_keywords_json() + for level, entries in table.items(): + for symbol, doc in entries.items(): + for match in doc.get("keyword_matches") or []: + keyword = str(match.get("keyword") or "").strip() + if not keyword: + continue + key = keyword.casefold() + entry = ( + level, + symbol, + float(match.get("match_score") or 0.0), + keyword, + "keyword", + ) + by_keyword.setdefault(key, []).append(entry) + topic_id = match.get("topic_id") + if topic_id: + for variant in _topic_id_variants(str(topic_id)): + by_topic.setdefault(variant, []).append(entry) + + for match in doc.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + entry = ( + level, + symbol, + float(match.get("match_score") or 0.0), + str(match.get("topic_display_name") or topic_id), + "topic", + ) + for variant in _topic_id_variants(str(topic_id)): + by_topic.setdefault(variant, []).append(entry) + + return by_keyword, by_topic + + +def clear_reverse_lookup_caches() -> None: + _build_json_inverted_index.cache_clear() + _topic_id_to_hierarchy.cache_clear() + _legacy_indices.cache_clear() + + +def _merge_ipc_match( + matches: dict[tuple[str, str], IpcCodeMatch], + level: str, + symbol: str, + score: float, + source_keyword: str, + match_type: str, +) -> None: + key = (level, normalize_symbol(symbol)) + existing = matches.get(key) + if existing is None or score > existing.match_score: + matches[key] = IpcCodeMatch( + ipc_level=level, + ipc_symbol=normalize_symbol(symbol), + match_score=score, + source_keyword=source_keyword, + match_type=match_type, + ) + + +def _matches_from_doc( + doc: dict[str, Any], + item: KeywordPatentSearchItem, +) -> list[IpcCodeMatch]: + ipc_level = str(doc.get("ipc_level") or "") + ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or "")) + if not ipc_level or not ipc_symbol: + return [] + + keyword_variants = set(_keyword_variants(item.keyword)) + topic_variants = set(_topic_id_variants(item.topic_id)) + topic_name = (item.topic_display_name or "").strip().casefold() + found: list[IpcCodeMatch] = [] + + for match in doc.get("keyword_matches") or []: + match_keyword = str(match.get("keyword") or "").strip() + if match_keyword.casefold() not in keyword_variants: + match_topic = match.get("topic_id") + if not match_topic or str(match_topic) not in topic_variants: + continue + score = _weighted_score( + ipc_level, + float(match.get("match_score") or 0.0), + item.relevance_score, + ) + found.append( + IpcCodeMatch( + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + match_score=score, + source_keyword=item.keyword, + match_type="keyword", + ) + ) + break + + for match in doc.get("topic_matches") or []: + match_topic = match.get("topic_id") + match_name = str(match.get("topic_display_name") or "").strip().casefold() + topic_hit = match_topic and str(match_topic) in topic_variants + name_hit = topic_name and match_name == topic_name + if not topic_hit and not name_hit: + continue + score = _weighted_score( + ipc_level, + float(match.get("match_score") or 0.0), + item.relevance_score, + ) + found.append( + IpcCodeMatch( + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + match_score=score, + source_keyword=item.keyword, + match_type="topic", + ) + ) + break + + return found + + +def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: + by_keyword, by_topic = _build_json_inverted_index() + merged: dict[tuple[str, str], IpcCodeMatch] = {} + + for item in items: + for level, symbol, base_score, source_keyword, match_type in by_keyword.get( + item.keyword.strip().casefold(), [] + ): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, match_type + ) + + for variant in _topic_id_variants(item.topic_id): + for level, symbol, base_score, source_keyword, match_type in by_topic.get( + variant, [] + ): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, match_type + ) + + return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + + +@lru_cache(maxsize=1) +def _topic_id_to_hierarchy() -> dict[str, dict[str, str]]: + result: dict[str, dict[str, str]] = {} + for info in _load_topic_cache().values(): + topic_id = info.get("topic_id") + if not topic_id: + continue + for variant in _topic_id_variants(str(topic_id)): + result[variant] = info + return result + + +@lru_cache(maxsize=1) +def _legacy_indices() -> tuple[ + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], +]: + """topic_id / topic_name / subfield / field -> (level, symbol, score).""" + by_topic_id: dict[str, list[tuple[str, str, float]]] = {} + by_topic_name: dict[str, list[tuple[str, str, float]]] = {} + by_subfield: dict[str, list[tuple[str, str, float]]] = {} + by_field: dict[str, list[tuple[str, str, float]]] = {} + cache = _load_topic_cache() + + mapping = load_ipc_openalex_mapping() + for level, entries in mapping.items(): + for symbol, mapped in entries.items(): + score = 0.55 + record = (level, normalize_symbol(symbol), score) + for variant in _topic_id_variants(mapped.topic_id): + by_topic_id.setdefault(variant, []).append(record) + if mapped.topic_display_name: + by_topic_name.setdefault( + mapped.topic_display_name.casefold(), [] + ).append(record) + + info = cache.get(mapped.topic_display_name or "") + if info: + subfield = str(info.get("subfield") or "").casefold() + field = str(info.get("field") or "").casefold() + if subfield: + by_subfield.setdefault(subfield, []).append(record) + if field: + by_field.setdefault(field, []).append(record) + + return by_topic_id, by_topic_name, by_subfield, by_field + + +def _hierarchy_for_item(item: KeywordPatentSearchItem) -> dict[str, str]: + for variant in _topic_id_variants(item.topic_id): + info = _topic_id_to_hierarchy().get(variant) + if info: + return info + if item.topic_display_name: + info = _load_topic_cache().get(item.topic_display_name) + if info: + return info + return { + "subfield": item.subfield_name or "", + "field": item.field_name or "", + } + + +def _apply_cs_ai_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + if field != "computer science" and subfield not in _AI_RELATED_SUBFIELDS: + return + + for symbol in _CS_AI_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.62, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _apply_automotive_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + keyword = item.keyword.casefold() + automotive_keyword = any( + token in keyword + for token in ( + "automobil", + "fahrzeug", + "kraftfahr", + "elektromob", + "verkehr", + "mobil", + ) + ) + if ( + subfield != "automotive engineering" + and field != "engineering" + and not automotive_keyword + ): + return + + for symbol in _AUTOMOTIVE_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.6, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _chemistry_subclasses_for_keyword(keyword: str) -> tuple[str, ...]: + normalized = keyword.casefold() + subclasses: list[str] = [] + if any(token in normalized for token in ("anorganisch", "inorganic")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_INORGANIC) + elif any(token in normalized for token in ("organisch", "organic")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) + if any(token in normalized for token in ("polymer", "makromolek")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_POLYMER) + if any(token in normalized for token in ("biochem", "enzym", "ferment")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM) + if any( + token in normalized + for token in ("analyt", "spektroskop", "chromatograph", "spektromet") + ): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL) + if any( + token in normalized + for token in ("verfahren", "reaktion", "katalys", "synthese", "technische chemie") + ): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_PROCESS) + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) + if any( + token in normalized + for token in ("chemie", "chemisch", "molekül", "molekul", "stoff") + ): + if not subclasses: + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_GENERAL) + return tuple(dict.fromkeys(subclasses)) + + +def _apply_chemistry_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + subclasses = _chemistry_subclasses_for_keyword(item.keyword) + if ( + subfield not in _CHEMISTRY_RELATED_SUBFIELDS + and field not in _CHEMISTRY_RELATED_FIELDS + and not subclasses + ): + return + + if not subclasses: + subclasses = _CHEMISTRY_IPC_SUBCLASSES_GENERAL + + for symbol in subclasses: + score = _weighted_score("subclass", 0.68, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _apply_medicine_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + keyword = item.keyword.casefold() + medicine_keyword = any( + token in keyword + for token in ( + "medizin", + "krankheit", + "therap", + "diagnos", + "patient", + "klinik", + "arzt", + "heilkund", + "pharma", + "immun", + "patholog", + ) + ) + if ( + subfield not in _MEDICINE_RELATED_SUBFIELDS + and field not in _MEDICINE_RELATED_FIELDS + and not medicine_keyword + ): + return + + for symbol in _MEDICINE_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.72, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _legacy_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: + by_topic_id, by_topic_name, by_subfield, by_field = _legacy_indices() + merged: dict[tuple[str, str], IpcCodeMatch] = {} + + for item in items: + for variant in _topic_id_variants(item.topic_id): + for level, symbol, base_score in by_topic_id.get(variant, []): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "topic" + ) + + topic_name = (item.topic_display_name or "").strip().casefold() + if topic_name: + for level, symbol, base_score in by_topic_name.get(topic_name, []): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "topic" + ) + + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + if subfield: + for level, symbol, base_score in by_subfield.get(subfield, []): + score = _weighted_score(level, base_score * 0.85, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "subfield" + ) + if field: + for level, symbol, base_score in by_field.get(field, []): + score = _weighted_score(level, base_score * 0.7, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "field" + ) + + results = sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + if not results: + logger.info( + "Legacy IPC lookup found no codes for %d keyword(s); " + "build patents_openalex_keywords for better coverage.", + len(items), + ) + return results + + +def _finalize_ipc_matches( + items: list[KeywordPatentSearchItem], + matches: list[IpcCodeMatch], +) -> list[IpcCodeMatch]: + merged: dict[tuple[str, str], IpcCodeMatch] = {} + for match in matches: + _merge_ipc_match( + merged, + match.ipc_level, + match.ipc_symbol, + match.match_score, + match.source_keyword, + match.match_type, + ) + for item in items: + _apply_cs_ai_heuristics(merged, item) + _apply_automotive_heuristics(merged, item) + _apply_chemistry_heuristics(merged, item) + _apply_medicine_heuristics(merged, item) + return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + + +def _build_es_should_clauses(items: list[KeywordPatentSearchItem]) -> list[dict[str, Any]]: + should: list[dict[str, Any]] = [] + seen: set[str] = set() + + for item in items: + for keyword in _keyword_variants(item.keyword): + if keyword in seen: + continue + seen.add(keyword) + should.append( + { + "nested": { + "path": "keyword_matches", + "query": {"term": {"keyword_matches.keyword": keyword}}, + } + } + ) + + for topic_id in _topic_id_variants(item.topic_id): + if topic_id in seen: + continue + seen.add(topic_id) + should.extend( + [ + { + "nested": { + "path": "keyword_matches", + "query": {"term": {"keyword_matches.topic_id": topic_id}}, + } + }, + { + "nested": { + "path": "topic_matches", + "query": {"term": {"topic_matches.topic_id": topic_id}}, + } + }, + ] + ) + + topic_name = (item.topic_display_name or "").strip() + if topic_name and topic_name not in seen: + seen.add(topic_name) + should.append( + { + "nested": { + "path": "topic_matches", + "query": { + "term": {"topic_matches.topic_display_name": topic_name} + }, + } + } + ) + + return should + + +class KeywordIpcReverseLookup: + def __init__(self, client: PatentsOpenAlexKeywordsClient | None = None): + self.client = client or PatentsOpenAlexKeywordsClient() + self._elasticsearch_checked = False + self._elasticsearch_enabled = False + + async def _elasticsearch_enabled_for_request(self) -> bool: + if self._elasticsearch_checked: + return self._elasticsearch_enabled + self._elasticsearch_checked = True + try: + self._elasticsearch_enabled = await self.client.index_exists() + except Exception as exc: + logger.warning("patents_openalex_keywords index check failed: %s", exc) + self._elasticsearch_enabled = False + return self._elasticsearch_enabled + + async def lookup_ipc_codes( + self, + items: list[KeywordPatentSearchItem], + *, + max_codes: int = 40, + ) -> list[IpcCodeMatch]: + if not items: + return [] + + matches: list[IpcCodeMatch] = [] + if await self._elasticsearch_enabled_for_request(): + try: + matches = await self._lookup_via_elasticsearch(items) + except (MissingApiKeyError, httpx.HTTPError) as exc: + logger.warning("Keyword IPC ES lookup failed, using JSON fallback: %s", exc) + self._elasticsearch_enabled = False + + if not matches: + matches = _json_lookup(items) + + if not matches: + matches = _legacy_lookup(items) + + if not matches: + logger.info( + "No IPC codes resolved for keywords: %s", + [item.keyword for item in items], + ) + + matches = _finalize_ipc_matches(items, matches) + heuristics = [match for match in matches if match.match_type == "heuristic"] + regular = [match for match in matches if match.match_type != "heuristic"] + regular = sorted(regular, key=lambda match: match.match_score, reverse=True) + remaining = max(0, max_codes - len(heuristics)) + return heuristics + regular[:remaining] + + async def _lookup_via_elasticsearch( + self, + items: list[KeywordPatentSearchItem], + ) -> list[IpcCodeMatch]: + should = _build_es_should_clauses(items) + if not should: + return [] + + payload = { + "size": 200, + "query": {"bool": {"should": should, "minimum_should_match": 1}}, + "_source": [ + "ipc_level", + "ipc_symbol", + "topic_matches", + "keyword_matches", + ], + } + + async with httpx.AsyncClient( + base_url=self.client.base_url, + timeout=self.client.timeout, + transport=self.client.transport, + ) as client: + response = await client.post( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search", + headers=self.client._headers(), + json=payload, + ) + response.raise_for_status() + data = response.json() + + merged: dict[tuple[str, str], IpcCodeMatch] = {} + for hit in data.get("hits", {}).get("hits", []): + doc = hit.get("_source", {}) + for item in items: + for match in _matches_from_doc(doc, item): + _merge_ipc_match( + merged, + match.ipc_level, + match.ipc_symbol, + match.match_score, + match.source_keyword, + match.match_type, + ) + + return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py new file mode 100644 index 00000000..86a3ce9b --- /dev/null +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -0,0 +1,166 @@ +"""Elasticsearch query builders for IPC-based patent search.""" +from __future__ import annotations + +from typing import Any + +from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE +from inse.patents.ipc_lookup import parse_ipc_symbol +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +_PATENT_SOURCE_FIELDS = [ + "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", +] + +_USPTO_SOURCE_FIELDS = [ + "publication_number", + "country", + "publication_date", + "publication_year", + "application_number", + "application_date", + "application_type", + "number_of_claims", + "status", + "title", + "abstract", + "inventors_names", + "assignees_orgs", + "ipcr", + "cpc", +] + +_MIN_MATCH_TERM_LEN = 4 + + +def _search_terms_for_symbol(symbol: str) -> list[str]: + """Derive EPO/USPTO `match` terms from an IPC/CPC symbol. + + Patent indices store IPC values like ``B60L 53/14 20060101AFI...``. + Wildcard/prefix on normalized symbols (``B60L*``) does not match; ``match`` + on subclass codes (``B60L``) does. + """ + normalized = normalize_symbol(symbol) + if not normalized: + return [] + + terms: list[str] = [] + subclass = infer_subclass(normalized) + if subclass and len(subclass) >= _MIN_MATCH_TERM_LEN: + terms.append(subclass) + + keys = parse_ipc_symbol(normalized) + if keys is not None: + if keys.subclass and len(keys.subclass) >= _MIN_MATCH_TERM_LEN: + terms.append(normalize_symbol(keys.subclass)) + if keys.main_group and len(normalize_symbol(keys.main_group)) >= _MIN_MATCH_TERM_LEN: + terms.append(normalize_symbol(keys.main_group)) + + if len(normalized) >= _MIN_MATCH_TERM_LEN: + prefix = normalized[:_MIN_MATCH_TERM_LEN] + if prefix not in terms: + terms.append(prefix) + + return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN)) + + +def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]: + clauses: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for term in terms: + if len(term) < _MIN_MATCH_TERM_LEN: + continue + key = (field, term) + if key in seen: + continue + seen.add(key) + clauses.append({"match": {field: term}}) + return clauses + + +class IpcPatentSearchQueries: + def epo_query_by_ipc_terms( + self, + terms: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": _PATENT_SOURCE_FIELDS, + "query": query, + } + + def uspto_query_by_ipc_terms( + self, + terms: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"publication_date": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": _USPTO_SOURCE_FIELDS, + "query": query, + } + + def epo_query_by_ipc_symbols( + self, + symbols: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + terms: list[str] = [] + seen: set[str] = set() + for symbol in symbols: + for term in _search_terms_for_symbol(symbol): + if term in seen: + continue + seen.add(term) + terms.append(term) + return self.epo_query_by_ipc_terms(terms, size=size) + + def uspto_query_by_ipc_symbols( + self, + symbols: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + terms: list[str] = [] + seen: set[str] = set() + for symbol in symbols: + for term in _search_terms_for_symbol(symbol): + if term in seen: + continue + seen.add(term) + terms.append(term) + return self.uspto_query_by_ipc_terms(terms, size=size) diff --git a/service/src/main/inse/patents/keywords/service.py b/service/src/main/inse/patents/keywords/service.py new file mode 100644 index 00000000..8aac2ea4 --- /dev/null +++ b/service/src/main/inse/patents/keywords/service.py @@ -0,0 +1,23 @@ +from typing import Annotated + +from fastapi import APIRouter, Body + +from inse.patents.keywords import logic +from inse.patents.keywords.model import PatentsByKeywordsRequest, PatentsByKeywordsResponse + +router = APIRouter(prefix="/api/inse-service/keywords", tags=["Keywords"]) + + +@router.post( + "/patents", + operation_id="getPatentsByKeywords", + response_model=PatentsByKeywordsResponse, + summary="Find patents matching extracted OpenAlex keywords.", +) +async def get_patents_by_keywords( + request: Annotated[ + PatentsByKeywordsRequest, + Body(description="Keywords enriched with OpenAlex topics."), + ], +): + return await logic.get_patents_by_keywords(request) diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py new file mode 100644 index 00000000..74817c6c --- /dev/null +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -0,0 +1,128 @@ +"""Tests for keyword-based patent search.""" +from __future__ import annotations + +from inse.patents.common import model +from inse.patents.keywords.logic import _patent_code_matches_symbol, _score_patent +from inse.patents.keywords.reverse_lookup import ( + IpcCodeMatch, + _finalize_ipc_matches, + _json_lookup, + _legacy_lookup, + _weighted_score, + clear_reverse_lookup_caches, +) +from inse.patents.keywords.model import KeywordPatentSearchItem +from inse.patents.keywords.search_queries import _search_terms_for_symbol + + +def test_patent_code_matches_symbol_prefix() -> None: + assert _patent_code_matches_symbol("G01S 5/02", "G01S") + assert _patent_code_matches_symbol("G01S5/02", "G01S") + assert not _patent_code_matches_symbol("H01L 21/02", "G01S") + + +def test_score_patent_uses_best_ipc_match() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["G01S 5/02"], + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"), + IpcCodeMatch("class", "G01", 0.5, "wireless", "topic"), + ] + result = _score_patent(patent, ipc_matches) + assert result is not None + score, keywords, symbols = result + assert score == 0.9 + assert "localization" in keywords + assert "G01S" in symbols + + +def test_weighted_score_applies_level_and_relevance() -> None: + score = _weighted_score("subclass", 0.8, 0.5) + assert score == round(0.8 * 0.85 * 0.5, 4) + + +def test_search_terms_use_subclass_prefix() -> None: + assert "B60R" in _search_terms_for_symbol("B60R2300/8086") + assert "G06N" in _search_terms_for_symbol("G06N") + + +def test_legacy_lookup_uses_chemistry_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Organische Chemie", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "C07C" in symbols + + +def test_legacy_lookup_uses_medicine_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Medizin", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "A61B" in symbols + + +def test_legacy_lookup_uses_cs_ai_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Klassifikation", + topic_id="https://openalex.org/T12072", + topic_display_name="Machine Learning and Algorithms", + subfield_name="Artificial Intelligence", + field_name="Computer Science", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "G06N" in symbols + + +def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None: + clear_reverse_lookup_caches() + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", + lambda: { + "subclass": { + "G01S": { + "ipc_level": "subclass", + "ipc_symbol": "G01S", + "keyword_matches": [ + { + "keyword": "wireless localization", + "match_score": 0.91, + "topic_id": "https://openalex.org/T12345", + } + ], + "topic_matches": [], + } + } + }, + ) + clear_reverse_lookup_caches() + + items = [ + KeywordPatentSearchItem( + keyword="wireless localization", + topic_id="https://openalex.org/T12345", + relevance_score=1.0, + ) + ] + matches = _json_lookup(items) + assert len(matches) == 1 + assert matches[0].ipc_symbol == "G01S" + assert matches[0].match_score > 0 diff --git a/service/src/main/inse/patents/patents_openalex_keywords/__init__.py b/service/src/main/inse/patents/patents_openalex_keywords/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/patents/patents_openalex_keywords/client.py b/service/src/main/inse/patents/patents_openalex_keywords/client.py new file mode 100644 index 00000000..57809df0 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/client.py @@ -0,0 +1,171 @@ +"""HTTP client for the patents_openalex_keywords Elasticsearch index.""" +from __future__ import annotations + +import json +import logging +from typing import Any + +import httpx + +from inse import config +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.patents_openalex_keywords.mapping import ( + PATENTS_OPENALEX_KEYWORDS_INDEX, + PATENTS_OPENALEX_KEYWORDS_MAPPING, +) + +logger = logging.getLogger(__name__) + +_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section") + + +class PatentsOpenAlexKeywordsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 10.0, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key + self.timeout = timeout + self.transport = transport + + def _headers(self, content_type: str = "application/json") -> dict[str, str]: + if not self.api_key: + raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") + return { + "Authorization": f"ApiKey {self.api_key}", + "Content-Type": content_type, + } + + async def ensure_index(self) -> None: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.head( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + ) + if response.status_code == 404: + create_response = await client.put( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + json={"mappings": PATENTS_OPENALEX_KEYWORDS_MAPPING}, + ) + create_response.raise_for_status() + logger.info("Created index %s", PATENTS_OPENALEX_KEYWORDS_INDEX) + return + + response.raise_for_status() + mapping_response = await client.put( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_mapping", + headers=self._headers(), + json=PATENTS_OPENALEX_KEYWORDS_MAPPING, + ) + mapping_response.raise_for_status() + + async def index_exists(self) -> bool: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.head( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + ) + if response.status_code == 404: + return False + response.raise_for_status() + return True + + async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None: + if not documents: + return + + batch_size = 500 + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + for start in range(0, len(documents), batch_size): + batch = documents[start : start + batch_size] + bulk_lines: list[str] = [] + for doc_id, source in batch: + bulk_lines.append( + json.dumps( + { + "index": { + "_index": PATENTS_OPENALEX_KEYWORDS_INDEX, + "_id": doc_id, + } + } + ) + ) + bulk_lines.append(json.dumps(source)) + + payload = "\n".join(bulk_lines) + "\n" + response = await client.post( + "/_bulk", + content=payload, + headers=self._headers("application/x-ndjson"), + params={"refresh": "true"}, + ) + response.raise_for_status() + result = response.json() + if result.get("errors"): + failed = [ + item + for item in result.get("items", []) + if item.get("index", {}).get("status", 200) >= 400 + ] + logger.error("Bulk index errors: %s", failed[:3]) + raise RuntimeError( + f"Bulk indexing into {PATENTS_OPENALEX_KEYWORDS_INDEX} failed." + ) + + async def lookup(self, level: str, symbol: str) -> dict[str, Any] | None: + normalized = symbol.strip().upper().replace(" ", "") + doc_id = f"{level}:{normalized}" + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_doc/{doc_id}", + headers=self._headers(), + ) + if response.status_code == 404: + return None + response.raise_for_status() + return response.json().get("_source") + + async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None: + from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass + + normalized = symbol.strip().upper().replace(" ", "") + candidates: list[tuple[str, str]] = [(level, normalized) for level in _LEVEL_LOOKUP_ORDER] + subclass = infer_subclass(normalized) + if subclass: + candidates.append(("subclass", subclass)) + if len(normalized) >= 3: + candidates.append(("class", normalized[:3])) + if normalized: + candidates.append(("section", normalized[:1])) + + seen: set[tuple[str, str]] = set() + for level, candidate in candidates: + key = (level, candidate) + if key in seen: + continue + seen.add(key) + doc = await self.lookup(level, candidate) + if doc is not None: + return doc + return None diff --git a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py new file mode 100644 index 00000000..b89ad79e --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py @@ -0,0 +1,207 @@ +"""Fetch unique IPC/CPC hierarchy symbols and labels from the ipc Elasticsearch index.""" +from __future__ import annotations + +import re +from collections import defaultdict + +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.patents.ipc_search_client import IPC_INDEX + +LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = ( + ("section", "cpc_section_number", "cpc_section_name"), + ("class", "cpc_class_number", "cpc_class_name"), + ("group", "cpc_group_number", "cpc_group_name"), + ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), +) +DEFAULT_BUILD_LEVELS = ("section", "class", "subclass", "group", "subgroup") + + +def normalize_symbol(symbol: str | None) -> str: + if not symbol: + return "" + return symbol.strip().upper().replace(" ", "") + + +def infer_subclass(symbol: str | None) -> str | None: + if not symbol: + return None + cleaned = normalize_symbol(symbol) + match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned) + return match.group(1) if match else None + + +def infer_class(symbol: str | None) -> str | None: + if not symbol: + return None + cleaned = normalize_symbol(symbol) + match = re.match(r"^([A-HY]\d{2})", cleaned) + return match.group(1) if match else None + + +def build_class_entries_from_subclasses( + subclass_entries: dict[str, str], + max_labels_per_class: int = 8, +) -> dict[str, str]: + labels_by_class: dict[str, list[str]] = defaultdict(list) + seen_labels_by_class: dict[str, set[str]] = defaultdict(set) + + for subclass_symbol, subclass_label in sorted(subclass_entries.items()): + class_symbol = infer_class(subclass_symbol) + if not class_symbol: + continue + + label = " ".join(subclass_label.split()) + label_key = label.casefold() + if label_key in seen_labels_by_class[class_symbol]: + continue + + seen_labels_by_class[class_symbol].add(label_key) + labels_by_class[class_symbol].append(f"{subclass_symbol}: {label}") + + class_entries: dict[str, str] = {} + for class_symbol, labels in labels_by_class.items(): + selected_labels = labels[:max_labels_per_class] + class_entries[class_symbol] = ( + f"IPC/CPC class {class_symbol}. Related subclasses: " + "; ".join(selected_labels) + ) + return class_entries + + +async def fetch_unique_ipc_entries( + levels: tuple[str, ...] = DEFAULT_BUILD_LEVELS, +) -> dict[str, dict[str, str]]: + entries: dict[str, dict[str, str]] = defaultdict(dict) + + async def _composite_with_label( + level: str, + number_field: str, + name_field: str, + page_size: int, + ) -> bool: + for field_name in (number_field, f"{number_field}.keyword"): + after_key: dict[str, str] | None = None + found_any = False + while True: + payload: dict[str, object] = { + "size": 0, + "aggs": { + "items": { + "composite": { + "size": page_size, + "sources": [ + {"symbol": {"terms": {"field": field_name}}}, + ], + }, + "aggs": { + "sample": { + "top_hits": {"size": 1, "_source": [name_field]}, + } + }, + } + }, + } + if after_key: + payload["aggs"]["items"]["composite"]["after"] = after_key + try: + data = await elasticsearch.search( + index=IPC_INDEX, + body=payload, + cluster=ESCluster.INSE, + ) + except Exception: + found_any = False + break + items = data.get("aggregations", {}).get("items", {}) + buckets = items.get("buckets", []) + if not buckets: + break + found_any = True + for bucket in buckets: + key = bucket.get("key", {}) + symbol = key.get("symbol") + hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) + if not symbol or not hits: + continue + name = hits[0].get("_source", {}).get(name_field) + if not name: + continue + normalized = normalize_symbol(str(symbol)) + if level == "subclass": + if len(normalized) <= 3: + continue + normalized = infer_subclass(str(symbol)) or normalized + entries[level][normalized] = str(name).strip() + after_key = items.get("after_key") + if not after_key: + break + if found_any: + return True + return False + + async def _terms_with_label( + level: str, + number_field: str, + name_field: str, + size: int, + ) -> None: + for field_name in (number_field, f"{number_field}.keyword"): + payload = { + "size": 0, + "aggs": { + "items": { + "terms": {"field": field_name, "size": size}, + "aggs": { + "sample": { + "top_hits": {"size": 1, "_source": [name_field]}, + } + }, + } + }, + } + try: + data = await elasticsearch.search( + index=IPC_INDEX, + body=payload, + cluster=ESCluster.INSE, + ) + except Exception: + continue + buckets = data.get("aggregations", {}).get("items", {}).get("buckets", []) + if buckets: + break + else: + return + for bucket in buckets: + symbol = bucket.get("key") + hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) + if not symbol or not hits: + continue + name = hits[0].get("_source", {}).get(name_field) + if not name: + continue + normalized = normalize_symbol(str(symbol)) + if level == "class" and len(normalized) != 3: + continue + if level == "subclass": + if len(normalized) <= 3: + continue + normalized = infer_subclass(str(symbol)) or normalized + entries[level][normalized] = str(name).strip() + + if "section" in levels: + await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) + if "subclass" in levels or "class" in levels: + await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000) + if "group" in levels: + if not await _composite_with_label("group", "cpc_group_number", "cpc_group_name", 1000): + await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) + if "subgroup" in levels: + if not await _composite_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 1000): + await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) + if "class" in levels: + subclass_entries = entries.get("subclass", {}) + entries["class"].update(build_class_entries_from_subclasses(subclass_entries)) + if "subclass" not in levels: + entries.pop("subclass", None) + return entries diff --git a/service/src/main/inse/patents/patents_openalex_keywords/mapping.py b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py new file mode 100644 index 00000000..8464dd30 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py @@ -0,0 +1,34 @@ +PATENTS_OPENALEX_KEYWORDS_INDEX = "patents_openalex_keywords" + +PATENTS_OPENALEX_KEYWORDS_MAPPING = { + "properties": { + "ipc_level": {"type": "keyword"}, + "ipc_symbol": {"type": "keyword"}, + "ipc_label": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "topic_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "subfield": {"type": "keyword"}, + "field": {"type": "keyword"}, + "domain": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "keyword_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "keyword": {"type": "keyword"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "match_method": {"type": "keyword"}, + "model_name": {"type": "keyword"}, + "built_at": {"type": "date"}, + } +} diff --git a/service/src/main/inse/patents/patents_openalex_keywords/matching.py b/service/src/main/inse/patents/patents_openalex_keywords/matching.py new file mode 100644 index 00000000..2467d4d6 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/matching.py @@ -0,0 +1,409 @@ +"""SentenceTransformer-based IPC/CPC → OpenAlex topic/keyword matching.""" +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import numpy as np +from sentence_transformers import SentenceTransformer + +from inse.config import settings +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.util import get_model + +logger = logging.getLogger(__name__) + +TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json" +MATCH_METHOD = "sentence_transformer" +TOPIC_VECTORS_INDEX = "topicvectors" + + +@dataclass(frozen=True) +class TopicCandidate: + topic_id: str + display_name: str + subfield: str | None = None + field: str | None = None + domain: str | None = None + + +@dataclass(frozen=True) +class KeywordCandidate: + keyword: str + topic_id: str + topic_display_name: str | None = None + + +def _data_dir() -> Path: + return Path(__file__).resolve().parents[4] / "data" + + +def load_topic_cache(cache_path: Path | None = None) -> list[TopicCandidate]: + path = cache_path or (_data_dir() / TOPIC_CACHE_FILENAME) + with path.open(encoding="utf-8") as handle: + raw = json.load(handle) + topics: list[TopicCandidate] = [] + for display_name, info in raw.items(): + topic_id = info.get("topic_id") + if not topic_id: + continue + topics.append( + TopicCandidate( + topic_id=str(topic_id), + display_name=display_name, + subfield=info.get("subfield"), + field=info.get("field"), + domain=info.get("domain"), + ) + ) + return topics + + +def topic_embedding_text(topic: TopicCandidate) -> str: + parts = [topic.display_name] + for label in (topic.subfield, topic.field, topic.domain): + if label: + parts.append(label) + return ". ".join(parts) + + +async def fetch_keyword_candidates() -> list[KeywordCandidate]: + candidates: list[KeywordCandidate] = [] + seen: set[tuple[str, str]] = set() + async for hit in elasticsearch.scan( + index="openalex-topics", + query={"match_all": {}}, + source=["id", "display_name", "keywords"], + cluster=ESCluster.NES, + ): + source = hit.get("_source", {}) + topic_id = source.get("id") + topic_name = source.get("display_name") + if not topic_id: + continue + keywords = source.get("keywords") or [] + if not isinstance(keywords, list): + keywords = [keywords] if keywords else [] + for keyword in keywords: + if not keyword or not str(keyword).strip(): + continue + key = (str(topic_id), str(keyword).strip().casefold()) + if key in seen: + continue + seen.add(key) + candidates.append( + KeywordCandidate( + keyword=str(keyword).strip(), + topic_id=str(topic_id), + topic_display_name=topic_name, + ) + ) + return candidates + + +def _normalize_rows(vectors: np.ndarray) -> np.ndarray: + norms = np.linalg.norm(vectors, axis=1, keepdims=True) + norms = np.where(norms == 0, 1.0, norms) + return vectors / norms + + +def top_k_indices(query_vector: np.ndarray, corpus_matrix: np.ndarray, k: int) -> list[tuple[int, float]]: + if corpus_matrix.size == 0: + return [] + scores = corpus_matrix @ query_vector + limit = min(k, len(scores)) + if limit <= 0: + return [] + top_idx = np.argpartition(-scores, limit - 1)[:limit] + top_idx = top_idx[np.argsort(-scores[top_idx])] + return [(int(idx), float(scores[idx])) for idx in top_idx] + + +class EmbeddingMatcher: + def __init__( + self, + model: SentenceTransformer | None = None, + min_score: float = 0.5, + batch_size: int = 64, + ): + self.model = model or get_model() + self.min_score = min_score + self.batch_size = batch_size + self.model_name = settings.sentence_transformers_model_name + self._topic_candidates: list[TopicCandidate] = [] + self._keyword_candidates: list[KeywordCandidate] = [] + self._topic_matrix: np.ndarray | None = None + self._keyword_matrix: np.ndarray | None = None + + def prepare_topics(self, topics: list[TopicCandidate]) -> None: + self._topic_candidates = topics + texts = [topic_embedding_text(topic) for topic in topics] + vectors = self.model.encode( + texts, + batch_size=self.batch_size, + show_progress_bar=True, + convert_to_numpy=True, + ) + self._topic_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32)) + + def prepare_keywords(self, keywords: list[KeywordCandidate]) -> None: + self._keyword_candidates = keywords + if not keywords: + self._keyword_matrix = np.empty((0, 0), dtype=np.float32) + return + texts = [item.keyword for item in keywords] + vectors = self.model.encode( + texts, + batch_size=self.batch_size, + show_progress_bar=True, + convert_to_numpy=True, + ) + self._keyword_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32)) + + def match_ipc_label( + self, + ipc_label: str, + top_k: int, + ) -> tuple[list[dict], list[dict]]: + query_vector = self.model.encode( + ipc_label, + convert_to_numpy=True, + ) + query_vector = query_vector / max(float(np.linalg.norm(query_vector)), 1e-9) + + topic_matches: list[dict] = [] + if self._topic_matrix is not None and len(self._topic_candidates): + for rank, (idx, score) in enumerate( + top_k_indices(query_vector, self._topic_matrix, top_k), + start=1, + ): + if score < self.min_score: + continue + topic = self._topic_candidates[idx] + topic_matches.append( + { + "rank": rank, + "topic_id": topic.topic_id, + "topic_display_name": topic.display_name, + "subfield": topic.subfield, + "field": topic.field, + "domain": topic.domain, + "match_score": round(score, 4), + } + ) + + keyword_matches: list[dict] = [] + if self._keyword_matrix is not None and len(self._keyword_candidates): + for rank, (idx, score) in enumerate( + top_k_indices(query_vector, self._keyword_matrix, top_k), + start=1, + ): + if score < self.min_score: + continue + keyword = self._keyword_candidates[idx] + keyword_matches.append( + { + "rank": rank, + "keyword": keyword.keyword, + "topic_id": keyword.topic_id, + "topic_display_name": keyword.topic_display_name, + "match_score": round(score, 4), + } + ) + + return topic_matches, keyword_matches + + +def build_documents( + ipc_entries: dict[str, dict[str, str]], + matcher: EmbeddingMatcher, + levels: tuple[str, ...], + top_k: int, +) -> list[tuple[str, dict]]: + built_at = datetime.now(timezone.utc).isoformat() + documents: list[tuple[str, dict]] = [] + label_cache: dict[str, tuple[list[dict], list[dict]]] = {} + + for level in levels: + for symbol, label in ipc_entries.get(level, {}).items(): + cache_key = label.casefold() + if cache_key not in label_cache: + label_cache[cache_key] = matcher.match_ipc_label(label, top_k=top_k) + topic_matches, keyword_matches = label_cache[cache_key] + if not topic_matches and not keyword_matches: + continue + doc_id = f"{level}:{symbol}" + documents.append( + ( + doc_id, + { + "ipc_level": level, + "ipc_symbol": symbol, + "ipc_label": label, + "topic_matches": topic_matches, + "keyword_matches": keyword_matches, + "match_method": MATCH_METHOD, + "model_name": matcher.model_name, + "built_at": built_at, + }, + ) + ) + return documents + + +def documents_to_json_mapping(documents: list[tuple[str, dict]]) -> dict[str, dict[str, dict]]: + mapping: dict[str, dict[str, dict]] = { + "section": {}, + "class": {}, + "subclass": {}, + "group": {}, + "subgroup": {}, + } + for _doc_id, source in documents: + level = source["ipc_level"] + symbol = source["ipc_symbol"] + mapping.setdefault(level, {})[symbol] = source + return mapping + + +class TopicVectorsMatcher: + + def __init__( + self, + model: SentenceTransformer | None = None, + min_score: float = 0.5, + num_candidates: int = 200, + ): + self.model = model or get_model() + self.min_score = min_score + self.num_candidates = num_candidates + self.model_name = settings.sentence_transformers_model_name + + async def _search_topic_vectors( + self, + *, + vector: list[float], + top_k: int, + ) -> list[dict[str, Any]]: + payload = { + "size": max(top_k * 4, top_k), + "_source": ["id", "display_name", "subfield", "field", "domain", "keywords"], + "knn": { + "field": "display_name_vector", + "query_vector": vector, + "k": max(top_k * 4, top_k), + "num_candidates": max(self.num_candidates, top_k * 8), + }, + } + data = await elasticsearch.search( + index=TOPIC_VECTORS_INDEX, + body=payload, + cluster=ESCluster.NES, + ) + return data.get("hits", {}).get("hits", []) or [] + + async def match_ipc_label( + self, + ipc_label: str, + top_k: int, + ) -> tuple[list[dict], list[dict]]: + vector = self.model.encode(ipc_label, convert_to_numpy=True) + query_vector = _normalize_rows(np.asarray([vector], dtype=np.float32))[0].tolist() + hits = await self._search_topic_vectors(vector=query_vector, top_k=top_k) + + topic_matches: list[dict] = [] + keyword_matches: list[dict] = [] + seen_topics: set[str] = set() + seen_keywords: set[tuple[str, str]] = set() + + for hit in hits: + source = hit.get("_source", {}) + topic_id = str(source.get("id") or "") + topic_name = str(source.get("display_name") or "") + if not topic_id or not topic_name or topic_id in seen_topics: + continue + score = float(hit.get("_score") or 0.0) + if score < self.min_score: + continue + + seen_topics.add(topic_id) + topic_matches.append( + { + "rank": len(topic_matches) + 1, + "topic_id": topic_id, + "topic_display_name": topic_name, + "subfield": source.get("subfield"), + "field": source.get("field"), + "domain": source.get("domain"), + "match_score": round(score, 4), + } + ) + + keywords = source.get("keywords") or [] + if not isinstance(keywords, list): + keywords = [keywords] if keywords else [] + for keyword in keywords: + normalized_keyword = str(keyword).strip() + if not normalized_keyword: + continue + key = (topic_id, normalized_keyword.casefold()) + if key in seen_keywords: + continue + seen_keywords.add(key) + keyword_matches.append( + { + "rank": len(keyword_matches) + 1, + "keyword": normalized_keyword, + "topic_id": topic_id, + "topic_display_name": topic_name, + "match_score": round(score, 4), + } + ) + break + + if len(topic_matches) >= top_k and len(keyword_matches) >= top_k: + break + + return topic_matches[:top_k], keyword_matches[:top_k] + + +async def build_documents_from_topicvectors( + ipc_entries: dict[str, dict[str, str]], + matcher: TopicVectorsMatcher, + levels: tuple[str, ...], + top_k: int, +) -> list[tuple[str, dict]]: + built_at = datetime.now(timezone.utc).isoformat() + documents: list[tuple[str, dict]] = [] + label_cache: dict[str, tuple[list[dict], list[dict]]] = {} + + for level in levels: + for symbol, label in ipc_entries.get(level, {}).items(): + cache_key = label.casefold() + if cache_key not in label_cache: + label_cache[cache_key] = await matcher.match_ipc_label(label, top_k=top_k) + topic_matches, keyword_matches = label_cache[cache_key] + if not topic_matches and not keyword_matches: + continue + doc_id = f"{level}:{symbol}" + documents.append( + ( + doc_id, + { + "ipc_level": level, + "ipc_symbol": symbol, + "ipc_label": label, + "topic_matches": topic_matches, + "keyword_matches": keyword_matches, + "match_method": "topicvectors_knn", + "model_name": matcher.model_name, + "built_at": built_at, + }, + ) + ) + return documents diff --git a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py new file mode 100644 index 00000000..bb33970b --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py @@ -0,0 +1,284 @@ +"""Runtime resolver for IPC/CPC → OpenAlex matches from patents_openalex_keywords.""" +from __future__ import annotations + +import json +import logging +import os +from functools import lru_cache + +from inse.patents.authors.ipc_openalex_mapping import ( + MappedOpenAlexTopic, + _enrich_mapped_topic, + load_ipc_openalex_mapping, + normalize_openalex_id, + resolve_mapped_topics_for_code, +) +from inse.patents.common import model +from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +logger = logging.getLogger(__name__) + +KEYWORDS_MAPPING_FILENAME = "patents_openalex_keywords_mapping.json" +_LEVEL_ORDER = {"subgroup": 5, "group": 4, "subclass": 3, "class": 2, "section": 1} + + +def _data_dir() -> str: + for base in ( + "/data", + os.path.normpath( + os.path.join( + os.path.dirname(__file__), + "..", + "..", + "..", + "..", + "data", + ) + ), + ): + if os.path.isdir(base): + return base + return os.path.normpath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data") + ) + + +@lru_cache(maxsize=1) +def load_patents_openalex_keywords_json() -> dict[str, dict[str, dict]]: + path = os.path.join(_data_dir(), KEYWORDS_MAPPING_FILENAME) + try: + with open(path, encoding="utf-8") as handle: + raw = json.load(handle) + except (OSError, json.JSONDecodeError): + return {} + if not isinstance(raw, dict): + return {} + return { + level: { + normalize_symbol(symbol): entry + for symbol, entry in (entries or {}).items() + if isinstance(entry, dict) + } + for level, entries in raw.items() + if isinstance(entries, dict) + } + + +def clear_resolver_caches() -> None: + load_patents_openalex_keywords_json.cache_clear() + + +def mapped_topics_from_index_doc(doc: dict) -> list[MappedOpenAlexTopic]: + seen: set[str] = set() + mapped: list[MappedOpenAlexTopic] = [] + ipc_level = doc.get("ipc_level") + ipc_symbol = doc.get("ipc_symbol") + + for match in doc.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + key = normalize_openalex_id(str(topic_id)) or str(topic_id) + if key in seen: + continue + seen.add(key) + mapped.append( + _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=match.get("topic_display_name"), + subfield_name=match.get("subfield"), + field_name=match.get("field"), + domain_name=match.get("domain"), + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + ) + ) + ) + + for match in doc.get("keyword_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + key = normalize_openalex_id(str(topic_id)) or str(topic_id) + if key in seen: + continue + seen.add(key) + mapped.append( + _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=match.get("topic_display_name"), + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + ) + ) + ) + + return mapped + + +def _json_lookup_symbol( + symbol: str, + table: dict[str, dict[str, dict]], +) -> dict | None: + normalized = normalize_symbol(symbol) + best_doc: dict | None = None + best_rank = -1 + + subclass = infer_subclass(normalized) + candidates: list[tuple[str, str]] = [ + ("subgroup", normalized), + ("group", normalized), + ] + if subclass: + candidates.append(("subclass", subclass)) + if len(normalized) >= 3: + candidates.append(("class", normalized[:3])) + if normalized: + candidates.append(("section", normalized[:1])) + + for level, candidate in candidates: + doc = table.get(level, {}).get(candidate) + if not doc: + continue + rank = _LEVEL_ORDER.get(level, 0) + if rank > best_rank: + best_rank = rank + best_doc = doc + + if best_doc is not None: + return best_doc + + for entries in table.values(): + if normalized in entries: + return entries[normalized] + return None + + +def _lookup_candidates(raw_code: str) -> list[str]: + symbol = extract_ipc_symbol(raw_code) + if not symbol: + return [] + + candidates: list[str] = [] + normalized = normalize_symbol(symbol) + if normalized: + candidates.append(normalized) + + keys = parse_ipc_symbol(symbol) or parse_ipc_symbol(normalized) + if keys is not None: + for value in ( + keys.subgroup or keys.normalized, + keys.main_group, + keys.subclass, + keys.ipc_class, + keys.section, + ): + if value: + candidates.append(normalize_symbol(value)) + + subclass = infer_subclass(normalized) + if subclass: + candidates.append(subclass) + + seen: set[str] = set() + ordered: list[str] = [] + for candidate in candidates: + if candidate and candidate not in seen: + seen.add(candidate) + ordered.append(candidate) + return ordered + + +class PatentOpenAlexMappingResolver: + """Resolve patent IPC/CPC codes via patents_openalex_keywords (ES → JSON → legacy).""" + + def __init__( + self, + client: PatentsOpenAlexKeywordsClient | None = None, + *, + use_elasticsearch: bool = True, + ): + self.client = client or PatentsOpenAlexKeywordsClient() + self.use_elasticsearch = use_elasticsearch + self._doc_cache: dict[str, dict | None] = {} + self._legacy_mapping = load_ipc_openalex_mapping() + self._elasticsearch_checked = False + self._elasticsearch_enabled = False + + async def resolve_topics_for_patents( + self, + patents: list[model.PatentEntry], + ) -> dict[str, list[MappedOpenAlexTopic]]: + from inse.patents.common.parsing import patent_map_key + + result: dict[str, list[MappedOpenAlexTopic]] = {} + for patent in patents: + result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent( + patent + ) + return result + + async def _elasticsearch_enabled_for_request(self) -> bool: + if not self.use_elasticsearch: + return False + if self._elasticsearch_checked: + return self._elasticsearch_enabled + self._elasticsearch_checked = True + try: + self._elasticsearch_enabled = await self.client.index_exists() + except Exception as exc: + logger.warning("patents_openalex_keywords index check failed: %s", exc) + self._elasticsearch_enabled = False + return self._elasticsearch_enabled + + async def resolve_mapped_topics_for_patent( + self, + patent: model.PatentEntry, + ) -> list[MappedOpenAlexTopic]: + seen: set[str] = set() + resolved: list[MappedOpenAlexTopic] = [] + for raw_code in (*patent.ipc, *patent.cpc): + for mapped in await self.resolve_mapped_topics_for_code(raw_code): + topic_key = normalize_openalex_id(mapped.topic_id) or mapped.topic_id + if topic_key in seen: + continue + seen.add(topic_key) + resolved.append(mapped) + return resolved + + async def resolve_mapped_topics_for_code(self, raw_code: str) -> list[MappedOpenAlexTopic]: + for candidate in _lookup_candidates(raw_code): + doc = await self._lookup_document(candidate) + if doc is not None: + mapped = mapped_topics_from_index_doc(doc) + if mapped: + return mapped + + return resolve_mapped_topics_for_code(raw_code, self._legacy_mapping) + + async def _lookup_document(self, symbol: str) -> dict | None: + normalized = normalize_symbol(symbol) + if normalized in self._doc_cache: + return self._doc_cache[normalized] + + doc: dict | None = None + if await self._elasticsearch_enabled_for_request(): + try: + doc = await self.client.lookup_symbol(normalized) + except Exception as exc: + logger.warning( + "patents_openalex_keywords ES lookup failed for %s: %s", + normalized, + exc, + ) + self._elasticsearch_enabled = False + + if doc is None: + doc = _json_lookup_symbol(normalized, load_patents_openalex_keywords_json()) + + self._doc_cache[normalized] = doc + return doc diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py new file mode 100644 index 00000000..66417433 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py @@ -0,0 +1,88 @@ +"""Tests for patents_openalex_keywords embedding matcher.""" +from __future__ import annotations + +import numpy as np +import pytest + +from inse.patents.patents_openalex_keywords.matching import ( + EmbeddingMatcher, + TopicCandidate, + top_k_indices, + topic_embedding_text, +) + + +def test_topic_embedding_text_joins_hierarchy() -> None: + topic = TopicCandidate( + topic_id="T1", + display_name="Cancer Immunotherapy", + subfield="Oncology", + field="Medicine", + domain="Health", + ) + assert topic_embedding_text(topic) == "Cancer Immunotherapy. Oncology. Medicine. Health" + + +def test_top_k_indices_returns_highest_scores() -> None: + corpus = np.array( + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.9, 0.1, 0.0], + ], + dtype=np.float32, + ) + corpus = corpus / np.linalg.norm(corpus, axis=1, keepdims=True) + query = np.array([1.0, 0.0, 0.0], dtype=np.float32) + + matches = top_k_indices(query, corpus, k=2) + assert len(matches) == 2 + assert matches[0][0] in {0, 2} + assert matches[0][1] >= matches[1][1] + + +class _FakeModel: + def encode(self, sentences, **kwargs): + del kwargs + if isinstance(sentences, str): + sentences = [sentences] + vectors = [] + for text in sentences: + lowered = text.casefold() + if "surgery" in lowered: + vectors.append(np.array([1.0, 0.0], dtype=np.float32)) + elif "immunotherapy" in lowered: + vectors.append(np.array([0.95, 0.05], dtype=np.float32)) + else: + vectors.append(np.array([0.0, 1.0], dtype=np.float32)) + arr = np.vstack(vectors) + if len(sentences) == 1 and isinstance(sentences[0], str): + return arr[0] + return arr + + +def test_embedding_matcher_returns_topic_and_keyword_matches() -> None: + matcher = EmbeddingMatcher(model=_FakeModel(), min_score=0.5) + matcher.prepare_topics( + [ + TopicCandidate(topic_id="T1", display_name="Cancer Immunotherapy"), + TopicCandidate(topic_id="T2", display_name="Unrelated Topic"), + ] + ) + from inse.patents.patents_openalex_keywords.matching import KeywordCandidate + + matcher.prepare_keywords( + [ + KeywordCandidate(keyword="surgery", topic_id="T9", topic_display_name="Surgery"), + KeywordCandidate(keyword="finance", topic_id="T8", topic_display_name="Finance"), + ] + ) + + topic_matches, keyword_matches = matcher.match_ipc_label( + "medical immunotherapy devices", + top_k=2, + ) + assert topic_matches + assert topic_matches[0]["topic_id"] == "T1" + assert keyword_matches + assert keyword_matches[0]["keyword"] == "surgery" diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py new file mode 100644 index 00000000..f46378de --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py @@ -0,0 +1,102 @@ +"""Tests for patents_openalex_keywords runtime resolver.""" +from __future__ import annotations + +import asyncio + +from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic +from inse.patents.authors.test_ipc_openalex_mapping import _author_with_topic +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.common import model +from inse.patents.patents_openalex_keywords.resolver import ( + PatentOpenAlexMappingResolver, + mapped_topics_from_index_doc, +) + + +def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None: + doc = { + "ipc_level": "subclass", + "ipc_symbol": "H01L", + "topic_matches": [ + { + "rank": 1, + "topic_id": "https://openalex.org/T99999", + "topic_display_name": "Semiconductor materials and devices", + "subfield": "Electrical Engineering", + } + ], + "keyword_matches": [ + { + "rank": 1, + "keyword": "silicon", + "topic_id": "https://openalex.org/T88888", + "topic_display_name": "Silicon Processing", + } + ], + } + mapped = mapped_topics_from_index_doc(doc) + assert len(mapped) == 2 + assert {item.topic_id for item in mapped} == { + "https://openalex.org/T99999", + "https://openalex.org/T88888", + } + + +class _FakeKeywordsClient: + def __init__(self, docs: dict[str, dict]): + self.docs = docs + + async def index_exists(self) -> bool: + return True + + async def lookup_symbol(self, symbol: str): + return self.docs.get(symbol) + + +def test_resolver_uses_index_doc_before_legacy_fallback() -> None: + resolver = PatentOpenAlexMappingResolver( + client=_FakeKeywordsClient( + { + "H01L": { + "ipc_level": "subclass", + "ipc_symbol": "H01L", + "topic_matches": [ + { + "topic_id": "https://openalex.org/T99999", + "topic_display_name": "Semiconductor materials and devices", + } + ], + "keyword_matches": [], + } + } + ), + use_elasticsearch=True, + ) + mapped = asyncio.run(resolver.resolve_mapped_topics_for_code("H01L 21/02")) + assert mapped + assert mapped[0].topic_id.endswith("T99999") + + +def test_filter_uses_patent_topic_map_from_resolver() -> None: + author = _author_with_topic( + "https://openalex.org/T99999", + "Semiconductor materials and devices", + ) + patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"]) + from inse.patents.common.parsing import patent_map_key + + topic_map = { + patent_map_key(patent): [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + topic_display_name="Semiconductor materials and devices", + ) + ] + } + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map=topic_map, + ) + assert len(filtered) == 1 diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 14d602a1..1844b05e 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -16,6 +16,10 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; import { OrgPatentsResponse, OrgPatentMatchTypeFilter } from '../model/orgPatentsResponse'; import { AllPatentsResponse } from '../model/allPatentsResponse'; +import { + PatentsByKeywordsRequest, + PatentsByKeywordsResponse, +} from '../model/patentsByKeywordsResponse'; export type { AllPatentsResponse }; @@ -402,4 +406,19 @@ export class PatentsService extends BaseService { headers: localVarHeaders, }); } + + public getPatentsByKeywords( + request: PatentsByKeywordsRequest, + ): Observable { + const localVarHeaders = this.defaultHeaders.set('Accept', 'application/json'); + const { basePath, withCredentials } = this.configuration; + return this.httpClient.post( + `${basePath}/api/inse-service/keywords/patents`, + request, + { + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + }, + ); + } } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts new file mode 100644 index 00000000..e2b8921a --- /dev/null +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -0,0 +1,26 @@ +import { PatentEntry } from './patentEntry'; + +export interface KeywordPatentSearchItem { + keyword: string; + topic_id?: string | null; + topic_display_name?: string | null; + subfield_name?: string | null; + field_name?: string | null; + relevance_score?: number; +} + +export interface PatentsByKeywordsRequest { + keywords: KeywordPatentSearchItem[]; +} + +export interface KeywordPatentMatch { + patent: PatentEntry; + match_score: number; + matched_keywords?: string[]; + matched_ipc_symbols?: string[]; +} + +export interface PatentsByKeywordsResponse { + patent_count: number; + patents: KeywordPatentMatch[]; +} diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html new file mode 100644 index 00000000..6d96b219 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -0,0 +1,114 @@ +@if (loading()) { +

Lade passende Patente...

+} @else if (error()) { +

Fehler beim Laden der Patente.

+} @else if (matches().length === 0) { +

Keine passenden Patente gefunden.

+} @else { +
+

Passende Patente

+ +
+
+
+ +
+ + + + + + + + + + + @for (item of pagedMatches(); track trackMatch($index, item)) { + + + + + + } + +
PatentQuelleJahr
+ {{ item.patent.title ?? item.patent.patent_id }} + + + {{ item.patent.source }} + + {{ item.patent.publication_year ?? '-' }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedPatent(); as patent) { +
+

{{ patent.title ?? patent.patent_id }}

+
+
+ Quelle + + + {{ patent.source }} + + +
+
+ Patent-Nr. + {{ patent.patent_id }} +
+
+ Datum + {{ + formatDate(patent.publication_date) + }} +
+ @if (getPublicationStageLabel(patent); as stageLabel) { +
+ Publikationsstufe + {{ stageLabel }} +
+ } +
+ + +
+ } +
+
+} diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss new file mode 100644 index 00000000..be8b1c24 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -0,0 +1,145 @@ +.message { + padding: 16px; + color: #666; +} + +.section-title { + margin: 0 0 16px; + font-size: 1.25rem; +} + +.patents-container { + margin-top: 1.5rem; + padding: 16px; + border-radius: 12px; + background: #fff; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); +} + +.sort-control { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 10px 14px; + border-radius: 20px; + background: #f2f2f2; + font-size: 14px; + + select { + border: 0; + background: transparent; + font: inherit; + cursor: pointer; + } +} + +.patents-content { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.patents-list { + flex: 1; + + table { + width: 100%; + border-collapse: collapse; + } + + th { + text-align: left; + padding: 10px 12px; + border-bottom: 2px solid #e0e0e0; + } + + tr { + cursor: pointer; + + &:hover { + background: #f5f5f5; + } + + &.selected { + background: #f0f0f0; + } + } + + td { + padding: 10px 12px; + border-bottom: 1px solid #eee; + } +} + +.patent-title { + font-weight: 500; +} + +.source-badge { + display: inline-block; + padding: 2px 8px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + + &--epo { + background: #dbeafe; + color: #1e40af; + } + + &--uspto { + background: #dcfce7; + color: #166534; + } +} + +.pagination { + display: flex; + align-items: center; + gap: 12px; + margin-top: 12px; +} + +.patent-detail { + flex: 0 0 320px; + padding: 16px; + border-radius: 12px; + background: #f8fafc; +} + +.detail-stats { + display: grid; + gap: 10px; + margin: 12px 0; +} + +.stat-label { + display: block; + font-size: 12px; + color: #666; +} + +.patent-detail-action { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + margin-top: 12px; + padding: 10px 12px; + border: 0; + border-radius: 8px; + background: #111827; + color: #fff; + cursor: pointer; +} + +@media (max-width: 900px) { + .patents-content { + flex-direction: column; + } + + .patent-detail { + flex: 1; + width: 100%; + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts new file mode 100644 index 00000000..4d11c1a2 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -0,0 +1,88 @@ +import { Component, input, signal } from '@angular/core'; +import { Router } from '@angular/router'; +import { PatentEntry } from '../../../api/model/patentEntry'; +import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../../patent-detail/patent-detail.utils'; + +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-keywords-patents', + templateUrl: './keywords-patents.component.html', + styleUrl: './keywords-patents.component.scss', +}) +export class KeywordsPatentsComponent { + readonly matches = input([]); + readonly loading = input(false); + readonly error = input(false); + + activeFilter = signal('all'); + selectedPatent = signal(null); + selectedPage = signal(1); + readonly pageSize = 10; + + constructor(private readonly router: Router) {} + + filteredMatches(): KeywordPatentMatch[] { + const filter = this.activeFilter(); + const items = this.matches(); + if (filter === 'all') { + return items; + } + return items.filter((item) => item.patent.source === filter); + } + + pagedMatches(): KeywordPatentMatch[] { + const start = (this.selectedPage() - 1) * this.pageSize; + return this.filteredMatches().slice(start, start + this.pageSize); + } + + pageCount(): number { + return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize)); + } + + hasPagination(): boolean { + return this.pageCount() > 1; + } + + setFilter(filter: SourceFilter): void { + this.activeFilter.set(filter); + this.selectedPage.set(1); + this.selectedPatent.set(null); + } + + setPage(page: number): void { + this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent.set(patent); + } + + openDetail(): void { + const patent = this.selectedPatent(); + if (!patent) return; + void this.router.navigate(['/patent', patent.patent_id]); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + trackMatch(_index: number, item: KeywordPatentMatch): string { + const patent = item.patent; + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index e313d794..de1aa15d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -385,11 +385,11 @@
-
+
+
+ + @if (showPatents()) { + + + } } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 15e6e6c5..e5afef70 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -419,16 +419,23 @@ mat-button-toggle-group { ============================================================ */ .search-container { display: flex; + flex-wrap: wrap; justify-content: center; + gap: 1rem; margin-top: 0.5rem; } -.search-btn { - min-width: 240px; +.action-btn { + min-width: 200px; align-self: center; min-height: $touch-target; } +.patents-btn { + background: #0f766e !important; + color: #fff !important; +} + @media (max-width: $phone) { .search-container { position: sticky; @@ -439,7 +446,7 @@ mat-button-toggle-group { box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08); } - .search-btn { + .action-btn { width: 100%; } } @@ -465,7 +472,7 @@ mat-button-toggle-group { width: 100%; justify-content: center; } - .search-btn { + .action-btn { width: 100%; } } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index a4442326..fbf9e4ef 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -45,6 +45,12 @@ import { } from '../../resolvers/utils/topic-legend'; import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; +import { PatentsService } from '../../api/api/patents.service'; +import { + KeywordPatentMatch, + KeywordPatentSearchItem, +} from '../../api/model/patentsByKeywordsResponse'; +import { KeywordsPatentsComponent } from './keywords-patents/keywords-patents.component'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -70,6 +76,7 @@ type KeywordView = 'llm' | 'topic'; MatTooltipModule, A11yModule, NgTemplateOutlet, + KeywordsPatentsComponent, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', @@ -81,6 +88,7 @@ export class KeywordsSearchComponent { private readonly destroyRef = inject(DestroyRef); private readonly websocketService = inject(KeywordWebSocketService); private readonly topicsService = inject(TopicsService); + private readonly patentsService = inject(PatentsService); readonly form = this.formBuilder.nonNullable.group({ selectedInputType: 'url' as InputMode, @@ -115,6 +123,11 @@ export class KeywordsSearchComponent { readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); readonly showVisualization = signal(false); + readonly showPatents = signal(false); + readonly patentMatches = signal([]); + readonly loadingPatents = signal(false); + readonly patentsError = signal(false); + readonly patentsLoaded = signal(false); readonly keywordsExist = computed( () => @@ -234,6 +247,10 @@ export class KeywordsSearchComponent { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); + this.patentMatches.set([]); + this.patentsLoaded.set(false); + this.patentsError.set(false); + this.showPatents.set(false); this.websocketService.close(); this.isExtracting.set(false); this.loadingNewKeyword.set(false); @@ -449,6 +466,10 @@ export class KeywordsSearchComponent { this.manualKeywordEntries.set([]); this.sourceContent.set(''); this.sourceUrl.set(null); + this.patentMatches.set([]); + this.patentsLoaded.set(false); + this.patentsError.set(false); + this.showPatents.set(false); // Keep only selected keywords that are in the manual list const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); @@ -553,21 +574,20 @@ export class KeywordsSearchComponent { search(): void { this.showVisualization.set(false); - const payload = { - extractedKeywords: this.getSelectedExtractedKeywordEntries(), - manualKeywords: this.getSelectedManualKeywordEntries(), - keywords: this.selectedKeywords(), - }; - - console.log('searching for keywords:', payload); - // e.g. navigate to search results page with the full payload in navigation state - // this.router.navigate(['/search'], { state: payload }); + this.showPatents.set(false); } visualize(): void { + this.showPatents.set(false); this.showVisualization.set(true); } + loadPatentsForSelection(): void { + this.showVisualization.set(false); + this.showPatents.set(true); + this.loadMatchingPatents(); + } + // --- Helpers -------------------------------------------------------------- private applyExtractedKeywords(keywords: ExtractedKeywords): void { @@ -993,4 +1013,50 @@ export class KeywordsSearchComponent { return 50; // fallback for unknown steps } } + + private loadMatchingPatents(): void { + const entries = [ + ...this.getSelectedExtractedKeywordEntries(), + ...this.getSelectedManualKeywordEntries(), + ]; + const keywords = this.buildPatentSearchItems(entries); + if (keywords.length === 0) { + this.patentMatches.set([]); + this.patentsLoaded.set(true); + return; + } + + this.loadingPatents.set(true); + this.patentsError.set(false); + + this.patentsService.getPatentsByKeywords({ keywords }).subscribe({ + next: (response) => { + this.patentMatches.set(response.patents ?? []); + this.patentsLoaded.set(true); + this.loadingPatents.set(false); + }, + error: (error) => { + console.error('Patent search failed:', error); + this.patentMatches.set([]); + this.patentsLoaded.set(true); + this.patentsError.set(true); + this.loadingPatents.set(false); + }, + }); + } + + private buildPatentSearchItems( + entries: KeywordEntryWithTopic[], + ): KeywordPatentSearchItem[] { + return entries + .map((entry) => ({ + keyword: entry.llm_keyword.keyword, + topic_id: entry.topic_mapping?.topic?.id ?? null, + topic_display_name: entry.topic_mapping?.topic?.display_name ?? null, + subfield_name: entry.topic_mapping?.topic?.subfield?.display_name ?? null, + field_name: entry.topic_mapping?.topic?.field?.display_name ?? null, + relevance_score: entry.llm_keyword.relevance_score ?? 1, + })) + .filter((item) => item.keyword.trim().length > 0); + } } From fa43ff8106840cfe84032583661b7b0893e837ae Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 9 Jul 2026 16:01:55 +0200 Subject: [PATCH 27/60] fix: add patent_map_key and resolver topic-map support for tests --- .../patents/authors/ipc_openalex_mapping.py | 191 +++++++++++++++++- .../src/main/inse/patents/authors/logic.py | 25 ++- .../inse/patents/authors/search_queries.py | 62 ++++++ .../authors/test_ipc_openalex_mapping.py | 69 +++++++ .../main/inse/patents/authors/topic_filter.py | 43 +++- .../src/main/inse/patents/common/parsing.py | 62 ++++++ .../patents/test_elastic_search_client.py | 17 +- service/src/main/inse/patents/test_logic.py | 70 ++++++- 8 files changed, 521 insertions(+), 18 deletions(-) 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 From ea3ddabac034c39f0d9bb8161b22412d02c4e451 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 23:28:40 +0200 Subject: [PATCH 28/60] file upload integration fixes --- .../keywords-search.component.html | 178 ++++++++++-------- .../keywords-search.component.scss | 7 +- .../keywords-search.component.ts | 92 ++++----- 3 files changed, 148 insertions(+), 129 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 8e50afb9..a8f41190 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -58,17 +58,14 @@
+ +
-
- - Topic Mapping - +
+ + Topic Mapping + +
@@ -276,36 +273,48 @@
- + @if (isExtracting() && broadKeywords().length === 0) { + + } @else { + + }
- + @if (isExtracting() && coarseKeywords().length === 0) { + + } @else { + + }
- + @if (isExtracting() && fineKeywords().length === 0) { + + } @else { + + }
@@ -322,14 +331,18 @@ {{ broadKeywords().length }}
- + @if (isExtracting() && broadKeywords().length === 0) { + + } @else { + + }
@@ -339,14 +352,18 @@ {{ coarseKeywords().length }}
- + @if (isExtracting() && coarseKeywords().length === 0) { + + } @else { + + }
@@ -356,14 +373,18 @@ {{ fineKeywords().length }}
- + @if (isExtracting() && fineKeywords().length === 0) { + + } @else { + + }
@@ -378,30 +399,27 @@ } - - - @if (sourceContent().length > 0) { - - - - Quellentext: {{ sourceUrl() }} - -
-
- } - @if (isExtracting() && !keywordsExist()) { + + + @if (sourceContent().length > 0) { + + + + Quellentext: {{ sourceUrl() }} + +
+
} - @if (isExtracting() && keywordsExist()) { + @if (isExtracting()) {
{{ statusMessage() }}
}
diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 5aa71fe2..b9692f90 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -22,7 +22,9 @@ $touch-target: 44px; margin-top: 0.5rem; gap: 0.5rem; align-items: top; - justify-content: center; + app-file-upload { + width: 100%; + } } .full-width { @@ -87,7 +89,6 @@ $touch-target: 44px; gap: auto; ::ng-deep .mdc-switch { - position: relative; width: 100%; } ::ng-deep .mdc-form-field { @@ -564,7 +565,7 @@ mat-button-toggle-group { SOURCE EXPANSION PANEL ============================================================ */ .source-expansion { - margin: 0.75rem 0; + margin: 0.5rem 1rem; background: var(--sg-background-muted, #f5f5f5); border-radius: 4px; //border-left: 4px solid var(--sg-primary, #1976d2); diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 5987992e..3bf8947e 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -152,39 +152,58 @@ export class KeywordsSearchComponent { let highlightedContent = content; - // replace the keyword with highlighted spans + const normalizeText = (text: string): string => { + return text + .trim() + .toLowerCase() + .replace(/[\u2010-\u2015\u2026—–]/g, '-') + .replace(/[\u2018\u2019\u201b\u201c\u201d\u201f]/g, "'") + .replace(/[\s\n\r\t]+/g, ' ') + .replace(/[^a-zA-Z0-9\s\-]/g, ''); + }; + + // Normalize keyword for matching + const normalizeKeyword = (keyword: string): string => { + return keyword + .trim() + .toLowerCase() + .replace(/[\s\-]+/g, '') + .replace(/[^a-zA-Z0-9]/g, ''); + }; + for (const keyword of selectedKeywords) { - const normalizedKeyword = this.normalizeKeyword(keyword); + const normalizedKeyword = normalizeKeyword(keyword); - // Find the first keyword entry that matches this normalized keyword - const entry = this.allKeywordEntries().find( - (e) => - this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword, - ); + const entry = this.allKeywordEntries().find((e) => { + const label = this.getKeywordLabel(e); + return normalizeKeyword(label) === normalizedKeyword; + }); - if (entry) { - const topic = this.getTopic(entry); - if (topic) { - const color = this.getTopicColor(topic); - // Escape HTML special characters in the keyword before using it in HTML - const escapedKeyword = keyword - .replace(/&/g, '&') - .replace(//g, '>'); + if (!entry) continue; - // Create the replacement span HTML - const replacement = `${escapedKeyword}`; + const topic = this.getTopic(entry); + if (!topic) continue; - const escapedRegexKeyword = keyword.replace( - /[.*+?^${}()|[\]\\]/g, - '\\$&', - ); - const regex = new RegExp(escapedRegexKeyword, 'g'); + const color = this.getTopicColor(topic); - highlightedContent = highlightedContent.replace(regex, replacement); - } - } + const escapedKeyword = keyword + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + + const escapedRegexKeyword = keyword + .replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + .replace(/\s+/g, '\\s*'); + + const regex = new RegExp(escapedRegexKeyword, 'gi'); + + const replacement = `${escapedKeyword}`; + + highlightedContent = highlightedContent.replace(regex, replacement); } + return this.sanitizer.bypassSecurityTrustHtml(highlightedContent); }); @@ -378,13 +397,6 @@ export class KeywordsSearchComponent { this.uploadedFiles.set(files); } - // Helper: Update progress bar - private updateProgress(processed: number, total: number) { - const progress = Math.round((processed / total) * 100); - this.progress.set(progress); - this.statusMessage.set(`Reading ${processed}/${total} files...`); - } - // Helper: Send files to WebSocket for server-side extraction private sendFilesToWebSocket(files: FileUpload[]) { const keywordsRequest: KeywordsRequest = { @@ -407,17 +419,6 @@ export class KeywordsSearchComponent { this.isExtracting.set(false); }); } - - onUploadProgress(event: { id: string; progress: number }) { - console.log('Upload progress:', event.progress + '%'); - this.progress.set(event.progress); - } - - onUploadError(error: { id: string; error: string }) { - console.error('Upload error:', error); - this.statusMessage.set('Upload failed: ' + error.error); - this.isExtracting.set(false); - } // --- Keyword selection & manual entry ------------------------------------ private keywordExists(keyword: string): boolean { @@ -589,6 +590,7 @@ export class KeywordsSearchComponent { } onExtractKeywordsClick(): void { + this.clearKeywords(); if (this.isExtracting()) { this.cancelKeywordExtraction(); return; @@ -626,7 +628,6 @@ export class KeywordsSearchComponent { }; processedFiles++; - this.updateProgress(processedFiles, totalFiles); if (processedFiles === totalFiles) { this.sendFilesToWebSocket(fileUploads); @@ -642,7 +643,6 @@ export class KeywordsSearchComponent { }; processedFiles++; - this.updateProgress(processedFiles, totalFiles); if (processedFiles === totalFiles) { this.sendFilesToWebSocket(fileUploads); From e5cf17620a9ba71301802416416ff9134943ae36 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 9 Jul 2026 23:29:06 +0200 Subject: [PATCH 29/60] fixed layout for fileupload, added snackbars on errors --- .../ui/file-upload/file-upload.component.html | 142 +++++---- .../ui/file-upload/file-upload.component.scss | 288 +++++++++++------- .../ui/file-upload/file-upload.component.ts | 214 +++++-------- 3 files changed, 333 insertions(+), 311 deletions(-) diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.html b/webapp/src/app/shared/ui/file-upload/file-upload.component.html index b44016cd..5ed5c35c 100644 --- a/webapp/src/app/shared/ui/file-upload/file-upload.component.html +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.html @@ -1,16 +1,72 @@ -
- -
- attach_file -

Drag & drop files here or click to browse

- - Supported: {{ requiredFileType }} (Max: {{ maxFileSize / 1024 / 1024 }}MB, - {{ maxFiles }} files) - +
+ +
+
+ attach_file +

Drag & Drop Dateien hier oder klicken

+ + Unterstützt: {{ requiredFileType }} (Max: + {{ maxFileSize / 1024 / 1024 }}MB, {{ maxFiles }} Dateien) + +
+ + @if (files.length > 0) { + +
+ @for (file of files; track file.id) { +
+
+ @if (file.file.type.startsWith('image/')) { + Preview + } @else { + {{ getIcon(file.file.type) }} + } + +
+ + + +
+
+ + @if (file.progress > 0 && file.progress < 100) { +
+
+
+ } + +
{{ file.file.name }}
+
+ } +
+ }
@@ -25,64 +81,4 @@ multiple (change)="onFileChange($event)" style="display: none" /> - - - @if (files.length > 0) { -
- @for (file of files; track file.id) { - -
-
- @if (file.file.type.startsWith('image/')) { - Preview - } @else { - {{ - getIcon(file.file.type) - }} - } -
-
-
{{ file.file.name }}
-
- {{ (file.file.size / 1024 / 1024).toFixed(2) }} MB -
-
-
- - - @if (file.progress > 0) { -
- - {{ file.progress }}% -
- } - - -
- - - -
-
- } -
- }
diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.scss b/webapp/src/app/shared/ui/file-upload/file-upload.component.scss index 8ad94b72..a38350da 100644 --- a/webapp/src/app/shared/ui/file-upload/file-upload.component.scss +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.scss @@ -1,145 +1,223 @@ .file-upload-container { - width: 100%; - max-width: 600px; margin: 0 auto; -} - -.drop-zone { - border: 2px dashed #ccc; - border-radius: 12px; - padding: 40px 20px; - text-align: center; - cursor: pointer; - transition: all 0.3s ease; - background-color: #f9f9f9; - - .upload-icon { - font-size: 48px; - color: #1976d2; - margin-bottom: 12px; + display: flex; + width: 100%; + flex-direction: column; + gap: 12px; + position: relative; + .drop-zone-wrapper { + border: 2px dashed #ccc; + border-radius: 12px; + background-color: #f9f9f9; + height: 100%; } + .drop-zone { + max-width: 100%; + flex: 1; + min-height: 0; - .drop-text { - font-size: 16px; - color: #555; - margin-bottom: 8px; - } + padding: 40px 20px; + text-align: center; + cursor: pointer; + transition: all 0.3s ease; - .file-info { - font-size: 12px; - color: #888; - } - - &.drag-over { - border-color: #1976d2; - background-color: #e3f2fd; - } -} - -.file-list { - margin-top: 16px; -} - -.file-card { - margin-bottom: 12px; - border-radius: 8px; - overflow: hidden; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); - - .file-header { - display: flex; - align-items: center; - gap: 12px; - padding: 12px; - background-color: #f5f5f5; - } - - .file-preview { - width: 50px; - height: 50px; - border-radius: 8px; - overflow: hidden; display: flex; + flex-direction: column; align-items: center; justify-content: center; - background-color: #ddd; - img { - width: 100%; - height: 100%; - object-fit: cover; + .upload-icon { + font-size: 48px; + height: 48px; + width: 48px; + color: #1976d2; + margin-bottom: 12px; + transition: all 0.3s ease; } - .file-icon { - font-size: 32px; - color: #666; + .drop-text { + font-size: 16px; + color: #555; + margin-bottom: 8px; + transition: all 0.3s ease; } - mat-icon { - font-size: 32px; - color: #666; - } - } - - .file-info { - flex: 1; - font-size: 14px; - - .file-name { - font-weight: 500; - color: #333; - } - - .file-size { + .file-info { font-size: 12px; color: #888; } + + &.drag-over { + border-color: #1976d2; + background-color: #e3f2fd; + } } - .progress-container { - display: flex; + &.compact .drop-zone { + padding: 16px 20px; + + .upload-icon { + font-size: 28px; + height: 28px; + width: 28px; + margin-bottom: 6px; + } + + .drop-text { + font-size: 13px; + margin-bottom: 4px; + } + + .file-info { + font-size: 11px; + } + } + + // Compact horizontal file strip + .file-strip { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(90px, 2fr)); align-items: center; - gap: 8px; - padding: 8px 12px; - background-color: #e8f5e9; + justify-content: center; + overflow-x: auto; + overflow-y: hidden; + padding: 2px 2px 8px; - .progress-bar { - flex: 1; + &::-webkit-scrollbar { + height: 6px; } - .progress-text { - font-size: 12px; - color: #2e7d32; + &::-webkit-scrollbar-thumb { + background: #ccc; + border-radius: 3px; + } + + &::-webkit-scrollbar-track { + background: transparent; } } - .file-actions { + // Individual compact file chip + .file-chip { + flex: 0 0 auto; + width: 90px; display: flex; + flex-direction: column; + align-items: center; gap: 4px; - padding: 8px 12px; - background-color: #f0f0f0; - button { - padding: 4px; + .chip-thumb { + position: relative; + width: 60px; + height: 60px; + border-radius: 10px; + overflow: hidden; + background-color: #eef1f4; + border: 1px solid #e0e0e0; + display: flex; + align-items: center; + justify-content: center; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } + + mat-icon { + font-size: 28px; + height: 28px; + width: 28px; + color: #1976d2; + } + + .chip-overlay { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + gap: 2px; + background: rgba(0, 0, 0, 0.55); + opacity: 0; + transition: opacity 0.2s ease; + + .chip-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + padding: 0; + border: none; + background: transparent; + color: #fff; + cursor: pointer; + border-radius: 4px; + + &:hover { + background: rgba(255, 255, 255, 0.2); + } + + mat-icon { + font-size: 15px; + height: 15px; + width: 15px; + color: #fff; + } + } + } + + &:hover .chip-overlay, + &:focus-within .chip-overlay { + opacity: 1; + } + } + + .chip-progress { + width: 100%; + height: 3px; + border-radius: 2px; + background-color: #e0e0e0; + overflow: hidden; + + .chip-progress-fill { + height: 100%; + background-color: #1976d2; + transition: width 0.2s ease; + } + } + + .chip-name { + width: 100%; + font-size: 11px; + line-height: 1.3; + color: #333; + text-align: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } } } /* Responsive */ @media (max-width: 600px) { - .drop-zone { - padding: 30px 16px; + .file-upload-container { + gap: 10px; + height: 280px; } - .file-card { - .file-header { - flex-direction: column; - text-align: center; - } + .drop-zone { + padding: 24px 16px; + } - .file-preview { - width: 60px; - height: 60px; + .file-chip { + width: 64px; + + .chip-thumb { + width: 50px; + height: 50px; } } } diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.ts b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts index 40b52830..7250c72e 100644 --- a/webapp/src/app/shared/ui/file-upload/file-upload.component.ts +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts @@ -7,105 +7,94 @@ import { ElementRef, OnDestroy, OnInit, + inject, + effect, } from '@angular/core'; import { HttpClient, HttpEventType } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { finalize } from 'rxjs/operators'; - -import { MatCardModule } from '@angular/material/card'; -import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { MatChipsModule } from '@angular/material/chips'; +import { MatSnackBar } from '@angular/material/snack-bar'; import { MatDividerModule } from '@angular/material/divider'; export interface FileUploadItem { file: File; + id: string; previewUrl?: string; progress: number; error?: string; - id: string; } @Component({ selector: 'app-file-upload', - imports: [ - MatCardModule, - MatProgressBarModule, - MatIconModule, - MatTooltipModule, - MatChipsModule, - MatDividerModule, - ], + imports: [MatIconModule, MatTooltipModule, MatDividerModule], templateUrl: 'file-upload.component.html', styleUrls: ['file-upload.component.scss'], }) export class FileUploadComponent implements OnInit, OnDestroy { - @Input() - uploadUrl: string = ''; + private snackBar = inject(MatSnackBar); + private http = inject(HttpClient); - @Input() - requiredFileType: string | string[] = 'application/pdf'; + @Input() uploadUrl: string = ''; + @Input() uploadedFiles: FileUploadItem[] = []; + @Input() requiredFileType: string | string[] = 'application/pdf'; + @Input() maxFileSize: number = 10 * 1024 * 1024; // 10MB + @Input() maxFiles: number = 5; - @Input() - maxFileSize: number = 10 * 1024 * 1024; // 10MB - - @Input() - maxFiles: number = 5; - - @Input() - autoUpload: boolean = false; - - @Output() - filesSelected = new EventEmitter(); - - @Output() - uploadProgressChange = new EventEmitter<{ id: string; progress: number }>(); - - @Output() - uploadComplete = new EventEmitter(); - - @Output() - uploadError = new EventEmitter<{ id: string; error: string }>(); + @Output() filesChange = new EventEmitter(); + @Output() filesSelected = new EventEmitter(); + @Output() uploadProgressChange = new EventEmitter<{ + id: string; + progress: number; + }>(); @ViewChild('fileInput', { static: true }) fileInput!: ElementRef; - @ViewChild('dropZone', { static: true }) dropZone!: ElementRef; + @ViewChild('uploadContainer', { static: true }) + uploadContainer!: ElementRef; files: FileUploadItem[] = []; - uploadSub: Subscription = Subscription.EMPTY; - + private uploadSub: Subscription = new Subscription(); isDragging = false; - constructor(private http: HttpClient) {} + private dragCounter = 0; ngOnInit() { + this.files = [...this.uploadedFiles]; // bind the input files to the internal state this.setupDragAndDrop(); } ngOnDestroy() { - if (this.uploadSub) { - this.uploadSub.unsubscribe(); - } + this.uploadSub.unsubscribe(); } private setupDragAndDrop() { - const zone = this.dropZone.nativeElement; + const zone = this.uploadContainer.nativeElement; + + zone.addEventListener('dragenter', (e) => { + e.preventDefault(); + this.dragCounter++; + this.isDragging = this.dragCounter > 0; + }); zone.addEventListener('dragover', (e) => { e.preventDefault(); - this.isDragging = true; }); - zone.addEventListener('dragleave', () => { - this.isDragging = false; + zone.addEventListener('dragleave', (e) => { + e.preventDefault(); + this.dragCounter--; + this.isDragging = this.dragCounter > 0; }); zone.addEventListener('drop', (e) => { e.preventDefault(); + this.dragCounter = 0; this.isDragging = false; + const files = e.dataTransfer?.files; if (files) { this.handleFiles(files); @@ -120,40 +109,32 @@ export class FileUploadComponent implements OnInit, OnDestroy { } } - private handleFiles(files: FileList) { - if (this.files.length + 1 > this.maxFiles) { - this.uploadError.emit({ - id: this.generateId(), - error: `Maximum ${this.maxFiles} files allowed`, - }); - return; - } - const fileArray = Array.from(files); + private handleFiles(fileList: FileList) { const validFiles: File[] = []; + const newFiles: FileUploadItem[] = []; - fileArray.forEach((file) => { - if (!this.isValidFile(file)) { - return; - } + Array.from(fileList).forEach((file) => { + if (!this.isValidFile(file)) return; validFiles.push(file); }); - + console.log('Valid files:', validFiles); if (validFiles.length === 0) return; - const newFiles = validFiles.map((file) => ({ - file, - id: this.generateId(), - progress: 0, - previewUrl: this.getPreviewUrl(file), - })); + const remainingSlots = this.maxFiles - this.files.length; + const filesToAdd = validFiles.slice(0, remainingSlots); + + filesToAdd.forEach((file) => { + newFiles.push({ + file, + id: this.generateId(), + progress: 0, + previewUrl: this.getPreviewUrl(file), + }); + }); this.files = [...this.files, ...newFiles]; - + this.emitFilesChange(); this.filesSelected.emit(this.files); - - if (this.autoUpload) { - this.uploadAll(); - } } private isValidFile(file: File): boolean { @@ -173,26 +154,21 @@ export class FileUploadComponent implements OnInit, OnDestroy { }); if (!isValidType) { - this.uploadError.emit({ - id: this.generateId(), - error: `File type not allowed: ${file.name}`, - }); + this.showError(`Dateityp nicht erlaubt: ${file.name}`); return false; } if (size > this.maxFileSize) { - this.uploadError.emit({ - id: this.generateId(), - error: `File too large: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`, - }); + this.showError( + `File zu groß: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`, + ); return false; } if (this.files.length + 1 > this.maxFiles) { - this.uploadError.emit({ - id: this.generateId(), - error: `Maximum ${this.maxFiles} files allowed`, - }); + this.showError( + `Maximal ${this.maxFiles} Dateien erlaubt. Datei ${file.name} wurde nicht hinzugefügt.`, + ); return false; } @@ -200,8 +176,7 @@ export class FileUploadComponent implements OnInit, OnDestroy { } private getPreviewUrl(file: File): string | undefined { - const type = file.type; - if (type.startsWith('image/')) { + if (file.type.startsWith('image/')) { return URL.createObjectURL(file); } return undefined; @@ -212,64 +187,24 @@ export class FileUploadComponent implements OnInit, OnDestroy { } getIcon(fileType: string): string { - if (fileType.startsWith('image/')) { - return 'image'; - } - if (fileType === 'application/pdf') { - return 'picture_as_pdf'; - } - if (fileType.startsWith('text/')) { - return 'description'; - } + if (fileType.startsWith('image/')) return 'image'; + if (fileType === 'application/pdf') return 'picture_as_pdf'; + if (fileType.startsWith('text/')) return 'description'; return 'insert_drive_file'; } - uploadAll() { - if (!this.uploadUrl) { - console.error('Upload URL is required!'); - return; - } - - this.uploadSub = this.http - .post( - this.uploadUrl, - this.files.map((f) => f.file), - { - reportProgress: true, - observe: 'events', - }, - ) - .pipe(finalize(() => this.reset())) - .subscribe((event) => { - if (event.type === HttpEventType.UploadProgress) { - const index = Math.floor((event.loaded / event.total!) * 100); - const id = this.files[0]?.id; - if (id) { - this.files = this.files.map((f) => ({ - ...f, - progress: index, - })); - this.uploadProgressChange.emit({ id, progress: index }); - } - } - }); - } - cancelUpload(id: string) { const file = this.files.find((f) => f.id === id); if (file) { this.files = this.files.filter((f) => f.id !== id); - this.uploadError.emit({ id, error: 'Upload cancelled' }); + this.emitFilesChange(); + this.showError('Upload cancelled'); } } - reset() { - this.uploadSub.unsubscribe(); - this.uploadSub = Subscription.EMPTY; - } - removeFile(id: string) { this.files = this.files.filter((f) => f.id !== id); + this.emitFilesChange(); } downloadFile(id: string) { @@ -283,4 +218,17 @@ export class FileUploadComponent implements OnInit, OnDestroy { URL.revokeObjectURL(url); } } + + private emitFilesChange() { + this.filesChange.emit(this.files); + } + + private reset() { + this.uploadSub.unsubscribe(); + this.uploadSub = new Subscription(); + } + + private showError(message: string) { + this.snackBar.open(message, 'OK', { duration: 3000 }); + } } From d1802fa1f876200690928b7883aca5ac5121f475 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 10 Jul 2026 13:12:27 +0200 Subject: [PATCH 30/60] publication detail: paginate authors and institutions lists --- .../publication-detail.component.html | 55 ++++++++++++++++++- .../publication-detail.component.scss | 44 +++++++++++++++ .../publication-detail.component.ts | 30 ++++++++++ 3 files changed, 127 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 54cdc042..baf5cb60 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -142,7 +142,10 @@ @if (authorsExpanded) {
- @for (authorship of authors(); track authorship.author?.id) { + @for ( + authorship of pagedAuthors(); + track authorship.author?.id + ) {
{{ @@ -184,6 +187,27 @@

Keine Angaben vorhanden.

}
+ @if (authorsPageCount() > 1) { +
+ + {{ authorsPage + 1 }} / {{ authorsPageCount() }} + +
+ }
} @@ -362,7 +386,10 @@ @if (institutionsExpanded) {
- @for (institution of institutions(); track institution.id) { + @for ( + institution of pagedInstitutions(); + track institution.id + ) { + @if (institutionsPageCount() > 1) { +
+ + {{ institutionsPage + 1 }} / + {{ institutionsPageCount() }} + +
+ }
} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss index 463604b8..6c9b3334 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.scss +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -444,6 +444,50 @@ dd { font-size: 11px; } +.list-pagination { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + margin-top: 12px; +} + +.page-btn { + display: grid; + place-items: center; + width: 28px; + height: 28px; + border: 1px solid var(--sg-border); + border-radius: 8px; + background: none; + cursor: pointer; + color: var(--sg-text-muted); + transition: background 0.12s; + + &:hover:not(:disabled) { + background: var(--sg-surface-muted); + color: var(--sg-text); + } + + &:disabled { + opacity: 0.35; + cursor: default; + } + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.page-indicator { + font-size: 12px; + color: var(--sg-text-muted); + min-width: 36px; + text-align: center; +} + .institution-country { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index 72552ecc..0153993b 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -65,12 +65,20 @@ export class PublicationDetailComponent implements OnInit { fundingExpanded = false; linksExpanded = false; + authorsPage = 0; + readonly authorsPageSize = 10; + + institutionsPage = 0; + readonly institutionsPageSize = 5; + ngOnInit(): void { this.loading = true; this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ next: ({ publication }) => { this.publication = publication; + this.authorsPage = 0; + this.institutionsPage = 0; this.loading = false; }, error: () => { @@ -130,6 +138,28 @@ export class PublicationDetailComponent implements OnInit { return this.publication?.authorships ?? []; } + pagedAuthors(): Authorship[] { + return this.authors().slice( + this.authorsPage * this.authorsPageSize, + (this.authorsPage + 1) * this.authorsPageSize, + ); + } + + authorsPageCount(): number { + return Math.ceil(this.authors().length / this.authorsPageSize); + } + + pagedInstitutions(): InstitutionDetail[] { + return this.institutions().slice( + this.institutionsPage * this.institutionsPageSize, + (this.institutionsPage + 1) * this.institutionsPageSize, + ); + } + + institutionsPageCount(): number { + return Math.ceil(this.institutions().length / this.institutionsPageSize); + } + institutions(): InstitutionDetail[] { const institutions = new Map(); for (const authorship of this.authors()) { From f5bf3ecbe46393e5adf86992cb3942311f1f2029 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Fri, 10 Jul 2026 13:26:23 +0200 Subject: [PATCH 31/60] feat(keywords): show patents for extracted keywords --- service/scripts/build_ipc_openalex_mapping.py | 280 -- service/scripts/check_author_patents.py | 78 - service/scripts/diagnose_author_patents.py | 94 - service/scripts/diagnose_keyword_patents.py | 91 - .../diagnose_patents_openalex_keywords.py | 89 - .../src/data/ipc_openalex_topic_mapping.json | 2962 ----------------- service/src/main/inse/main.py | 2 + .../src/main/inse/patents/keywords/logic.py | 802 +++-- .../src/main/inse/patents/keywords/model.py | 8 + .../inse/patents/keywords/reverse_lookup.py | 407 +-- .../main/inse/patents/keywords/test_logic.py | 648 +++- .../api/model/patentsByKeywordsResponse.ts | 3 + .../keywords-patents.component.html | 246 +- .../keywords-patents.component.scss | 11 + .../keywords-patents.component.ts | 191 +- .../keywords-search.component.ts | 42 +- 16 files changed, 1521 insertions(+), 4433 deletions(-) delete mode 100644 service/scripts/build_ipc_openalex_mapping.py delete mode 100644 service/scripts/check_author_patents.py delete mode 100644 service/scripts/diagnose_author_patents.py delete mode 100644 service/scripts/diagnose_keyword_patents.py delete mode 100644 service/scripts/diagnose_patents_openalex_keywords.py delete mode 100644 service/src/data/ipc_openalex_topic_mapping.json diff --git a/service/scripts/build_ipc_openalex_mapping.py b/service/scripts/build_ipc_openalex_mapping.py deleted file mode 100644 index 2d6d43f6..00000000 --- a/service/scripts/build_ipc_openalex_mapping.py +++ /dev/null @@ -1,280 +0,0 @@ -#!/usr/bin/env python3 -""" -build_ipc_openalex_mapping.py — Build a 1:1 IPC/CPC → OpenAlex topic mapping file. - -Scans the `ipc` Elasticsearch index, matches each hierarchy level (section, class, -subclass, group, subgroup) to the closest OpenAlex topic from topic_hierarchy_cache.json, -and writes service/src/data/ipc_openalex_topic_mapping.json. - -Usage: - python scripts/build_ipc_openalex_mapping.py - python scripts/build_ipc_openalex_mapping.py --output ../src/data/ipc_openalex_topic_mapping.json - python scripts/build_ipc_openalex_mapping.py --min-score 0.35 - -Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials for the ipc index. -""" -from __future__ import annotations - -import argparse -import asyncio -import json -import logging -import re -import sys -from collections import defaultdict -from difflib import SequenceMatcher -from pathlib import Path - -current_dir = Path(__file__).resolve().parent -sys.path.insert(0, str(current_dir.parent / "src" / "main")) - -from inse.integrations import elasticsearch # noqa: E402 -from inse.model import ESCluster # noqa: E402 -from inse.patents.ipc_search_client import IPC_INDEX # noqa: E402 - -logger = logging.getLogger(__name__) - -LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = ( - ("section", "cpc_section_number", "cpc_section_name"), - ("class", "cpc_class_number", "cpc_class_name"), - ("group", "cpc_group_number", "cpc_group_name"), - ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), -) -BUILD_LEVELS = ("section", "class", "subclass") - - -def _normalize_symbol(symbol: str | None) -> str: - if not symbol: - return "" - return symbol.strip().upper().replace(" ", "") - - -def _infer_subclass(symbol: str | None) -> str | None: - if not symbol: - return None - cleaned = _normalize_symbol(symbol) - match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned) - return match.group(1) if match else None - - -def _load_topic_cache() -> list[dict]: - cache_path = current_dir.parent / "src" / "data" / "topic_hierarchy_cache.json" - with cache_path.open(encoding="utf-8") as handle: - raw = json.load(handle) - topics = [] - for display_name, info in raw.items(): - topics.append( - { - "display_name": display_name, - "topic_id": info.get("topic_id"), - "subfield": info.get("subfield"), - "field": info.get("field"), - "domain": info.get("domain"), - } - ) - return topics - - -def _tokenize(text: str) -> set[str]: - return {token for token in re.findall(r"[a-z0-9]+", text.casefold()) if len(token) > 2} - - -def _prepare_topics(topics: list[dict]) -> tuple[list[dict], dict[str, set[int]]]: - prepared: list[dict] = [] - index: dict[str, set[int]] = defaultdict(set) - for idx, topic in enumerate(topics): - labels = [ - topic["display_name"], - topic.get("subfield"), - topic.get("field"), - topic.get("domain"), - ] - tokens: set[str] = set() - for label in labels: - if label: - tokens |= _tokenize(label) - prepared.append({**topic, "_tokens": tokens, "_labels": [l for l in labels if l]}) - for token in tokens: - index[token].add(idx) - return prepared, index - - -def _score_label(ipc_label: str, topic: dict) -> float: - ipc_text = ipc_label.casefold() - ipc_tokens = _tokenize(ipc_label) - best = 0.0 - for candidate in topic["_labels"]: - candidate_text = candidate.casefold() - ratio = SequenceMatcher(None, ipc_text, candidate_text).ratio() - token_overlap = len(ipc_tokens & topic["_tokens"]) - token_score = token_overlap / max(len(ipc_tokens), 1) - best = max(best, ratio, token_score) - return best - - -def _best_topic_match( - ipc_label: str, - topics: list[dict], - topic_index: dict[str, set[int]], - min_score: float, -) -> dict | None: - ipc_tokens = _tokenize(ipc_label) - candidate_indices: set[int] = set() - for token in ipc_tokens: - candidate_indices |= topic_index.get(token, set()) - if not candidate_indices: - return None - - best_topic = None - best_score = 0.0 - for idx in list(candidate_indices)[:100]: - topic = topics[idx] - score = _score_label(ipc_label, topic) - if score > best_score: - best_score = score - best_topic = topic - if best_topic is None or best_score < min_score: - return None - return { - "topic_id": best_topic["topic_id"], - "topic_display_name": best_topic["display_name"], - "subfield": best_topic.get("subfield"), - "field": best_topic.get("field"), - "domain": best_topic.get("domain"), - "match_score": round(best_score, 3), - } - - -async def _fetch_unique_ipc_entries() -> dict[str, dict[str, str]]: - entries: dict[str, dict[str, str]] = defaultdict(dict) - - async def _terms_with_label( - level: str, - number_field: str, - name_field: str, - size: int, - ) -> None: - for field_name in (number_field, f"{number_field}.keyword"): - payload = { - "size": 0, - "aggs": { - "items": { - "terms": {"field": field_name, "size": size}, - "aggs": { - "sample": { - "top_hits": {"size": 1, "_source": [name_field]}, - } - }, - } - }, - } - try: - data = await elasticsearch.search( - index=IPC_INDEX, - body=payload, - cluster=ESCluster.INSE, - ) - except Exception: - continue - buckets = data.get("aggregations", {}).get("items", {}).get("buckets", []) - if buckets: - break - else: - return - for bucket in buckets: - symbol = bucket.get("key") - hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) - if not symbol or not hits: - continue - name = hits[0].get("_source", {}).get(name_field) - if not name: - continue - normalized = _normalize_symbol(str(symbol)) - if level == "class" and len(normalized) != 3: - continue - if level == "subclass": - if len(normalized) <= 3: - continue - normalized = _infer_subclass(str(symbol)) or normalized - entries[level][normalized] = str(name).strip() - - if "section" in BUILD_LEVELS: - await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) - if "class" in BUILD_LEVELS: - await _terms_with_label("class", "cpc_class_number", "cpc_class_name", 500) - if "subclass" in BUILD_LEVELS: - await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000) - if "group" in BUILD_LEVELS: - await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) - if "subgroup" in BUILD_LEVELS: - await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) - return entries - - -def build_mapping(ipc_entries: dict[str, dict[str, str]], topics: list[dict], min_score: float) -> dict: - prepared_topics, topic_index = _prepare_topics(topics) - mapping = {level: {} for level in ("section", "class", "subclass", "group", "subgroup")} - label_cache: dict[tuple[str, str], dict | None] = {} - total = sum(len(symbols) for level, symbols in ipc_entries.items() if level in BUILD_LEVELS) - processed = 0 - - for level in BUILD_LEVELS: - symbols = ipc_entries.get(level, {}) - for symbol, label in symbols.items(): - processed += 1 - if processed % 500 == 0: - logger.info("Mapped %d / %d ipc symbols", processed, total) - cache_key = (level, label.casefold()) - if cache_key not in label_cache: - label_cache[cache_key] = _best_topic_match( - label, prepared_topics, topic_index, min_score - ) - match = label_cache[cache_key] - if match is None: - continue - mapping[level][symbol] = { - "topic_id": match["topic_id"], - "topic_display_name": match["topic_display_name"], - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "ipc_label": label, - "match_score": match["match_score"], - } - return mapping - - -async def main() -> None: - parser = argparse.ArgumentParser(description="Build IPC/CPC → OpenAlex topic mapping JSON.") - parser.add_argument( - "--output", - default=str(current_dir.parent / "src" / "data" / "ipc_openalex_topic_mapping.json"), - help="Output JSON path", - ) - parser.add_argument( - "--min-score", - type=float, - default=0.35, - help="Minimum label similarity score for a 1:1 assignment", - ) - args = parser.parse_args() - - logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") - topics = _load_topic_cache() - logger.info("Loaded %d OpenAlex topics from cache", len(topics)) - - ipc_entries = await _fetch_unique_ipc_entries() - counts = {level: len(ipc_entries.get(level, {})) for level in BUILD_LEVELS} - logger.info("Fetched unique ipc symbols: %s", counts) - - mapping = build_mapping(ipc_entries, topics, args.min_score) - output_path = Path(args.output) - output_path.parent.mkdir(parents=True, exist_ok=True) - output_path.write_text(json.dumps(mapping, indent=2, ensure_ascii=True), encoding="utf-8") - - counts = {level: len(mapping[level]) for level in mapping} - logger.info("Wrote mapping to %s: %s", output_path, counts) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/service/scripts/check_author_patents.py b/service/scripts/check_author_patents.py deleted file mode 100644 index 2d6f37ac..00000000 --- a/service/scripts/check_author_patents.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -"""Quick check of patent counts for specific authors.""" -from __future__ import annotations - -import asyncio -import sys -from pathlib import Path - -current_dir = Path(__file__).resolve().parent -sys.path.insert(0, str(current_dir.parent / "src" / "main")) - -from inse.patents.authors.ipc_openalex_mapping import clear_mapping_cache -from inse.patents.authors.logic import get_patents_by_author_id -from inse.patents.authors.name_matching import filter_patents_by_author_name -from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping -from inse.patents.authors.identity import is_ambiguous_name -from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits -from inse.patents.ipc_search_client import IpcSearchClient -from inse.patents.search_client import PatentSearchClient -from inse.persons import logic as person_logic - - -AUTHORS = [ - ("Dirk Schadendorf", "A5034365278", 8), - ("Christian Weber", "A5100603203", 14), -] - - -async def _counts(author_id: str) -> dict: - search_client = PatentSearchClient() - ipc_client = IpcSearchClient() - short_id = author_id.replace("https://openalex.org/", "") - person = await person_logic.search_persons(author_id=short_id) - author = person.results[0] if person.results else None - if not author or not author.display_name: - return {"error": "author not found"} - - epo_data, uspto_data = await asyncio.gather( - search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)), - search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)), - ) - all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) - name_matched = filter_patents_by_author_name(all_patents, author.display_name) - await enrich_patents_classifications(name_matched, ipc_client) - full_name_count = await person_logic.count_authors_by_display_name(author.display_name) - ambiguous = is_ambiguous_name( - author.display_name, - patent_hit_count=len(all_patents), - openalex_full_name_count=full_name_count, - ) - filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous) - return { - "author_name": author.display_name, - "es_hits": len(all_patents), - "name_matched": len(name_matched), - "after_topic_filter": len(filtered), - "ambiguous": ambiguous, - "openalex_same_name": full_name_count, - "titles": [item.patent.title for item in filtered], - } - - -async def main() -> None: - clear_mapping_cache() - for label, author_id, expected in AUTHORS: - result = await _counts(author_id) - print(f"\n=== {label} ({author_id}) expected={expected} ===") - for key, value in result.items(): - if key == "titles": - print(f"{key}:") - for title in value: - print(f" - {title}") - else: - print(f"{key}: {value}") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/service/scripts/diagnose_author_patents.py b/service/scripts/diagnose_author_patents.py deleted file mode 100644 index bd8961cf..00000000 --- a/service/scripts/diagnose_author_patents.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python3 -"""Per-patent breakdown of topic-filter decisions for test authors.""" -from __future__ import annotations - -import asyncio -import sys -from pathlib import Path - -current_dir = Path(__file__).resolve().parent -sys.path.insert(0, str(current_dir.parent / "src" / "main")) - -from inse.patents.authors.ipc_openalex_mapping import ( - clear_mapping_cache, - load_ipc_openalex_mapping, - patent_topics_match_author, - resolve_mapped_topics_for_patent, -) -from inse.patents.authors.name_matching import filter_patents_by_author_name -from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping -from inse.patents.authors.identity import is_ambiguous_name, patent_institution_match, patent_personal_assignee_match -from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits -from inse.patents.ipc_search_client import IpcSearchClient -from inse.patents.search_client import PatentSearchClient -from inse.persons import logic as person_logic - -AUTHORS = [ - ("Dirk Schadendorf", "A5034365278"), - ("Christian Weber", "A5100603203"), -] - - -async def diagnose(author_id: str) -> None: - search_client = PatentSearchClient() - ipc_client = IpcSearchClient() - short_id = author_id.replace("https://openalex.org/", "") - person = await person_logic.search_persons(author_id=short_id) - author = person.results[0] - mapping = load_ipc_openalex_mapping() - - print(f"\n{'='*70}") - print(f"{author.display_name} ({author_id})") - print("Author topics:") - for t in author.topics or []: - print(f" - {t.display_name} ({t.id})") - - institutions = [] - for inst in author.last_known_institutions or []: - institutions.append(inst.display_name) - for aff in author.affiliations or []: - if aff.institution: - institutions.append(aff.institution.display_name) - print("Institutions:", institutions) - - epo_data, uspto_data = await asyncio.gather( - search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)), - search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)), - ) - all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) - name_matched = filter_patents_by_author_name(all_patents, author.display_name) - await enrich_patents_classifications(name_matched, ipc_client) - full_name_count = await person_logic.count_authors_by_display_name(author.display_name) - ambiguous = is_ambiguous_name( - author.display_name, - patent_hit_count=len(all_patents), - openalex_full_name_count=full_name_count, - ) - print(f"ambiguous={ambiguous}, name_matched={len(name_matched)}") - - filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous) - kept_ids = {item.patent.patent_id for item in filtered} - - for i, patent in enumerate(name_matched, 1): - mapped = resolve_mapped_topics_for_patent(patent, mapping) - topic_match = patent_topics_match_author(patent, author, mapping) - inst_match = patent_institution_match(patent, institutions) - pers_match = patent_personal_assignee_match(patent, author.display_name or "") - kept = patent.patent_id in kept_ids - mapped_labels = [m.topic_display_name or m.topic_id for m in mapped] - ipc = patent.ipc[:3] if patent.ipc else [] - cpc = patent.cpc[:2] if patent.cpc else [] - print(f"\n[{i}] {'KEEP' if kept else 'DROP'} | {patent.title[:70] if patent.title else '?'}") - print(f" ipc={ipc} cpc={cpc}") - print(f" mapped={mapped_labels or 'NONE'}") - print(f" topic_match={topic_match} inst={inst_match} personal={pers_match}") - - -async def main() -> None: - clear_mapping_cache() - for label, author_id in AUTHORS: - await diagnose(author_id) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/service/scripts/diagnose_keyword_patents.py b/service/scripts/diagnose_keyword_patents.py deleted file mode 100644 index 7beeeb44..00000000 --- a/service/scripts/diagnose_keyword_patents.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -"""Diagnose keyword → patent search for a given keyword.""" -from __future__ import annotations - -import argparse -import asyncio -import sys -from pathlib import Path - -current_dir = Path(__file__).resolve().parent -sys.path.insert(0, str(current_dir.parent / "src" / "main")) - -from dotenv import load_dotenv - -load_dotenv(current_dir.parent / "src" / "main" / "inse" / ".env") - -from inse.patents.authors.ipc_openalex_mapping import _load_topic_cache -from inse.patents.keywords.logic import _patent_search_terms, get_patents_by_keywords -from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest -from inse.patents.keywords.reverse_lookup import KeywordIpcReverseLookup - - -def _find_topic(keyword: str) -> tuple[str, dict]: - cache = _load_topic_cache() - keyword_lower = keyword.casefold() - for name, info in cache.items(): - if keyword_lower in name.casefold(): - return name, info - for name, info in cache.items(): - if info.get("subfield", "").casefold() == keyword_lower: - return name, info - return keyword, {} - - -async def diagnose(keyword: str, topic_name: str | None, topic_id: str | None) -> None: - if topic_name and topic_id: - display_name = topic_name - tid = topic_id - info = _load_topic_cache().get(topic_name, {}) - else: - display_name, info = _find_topic(keyword) - tid = info.get("topic_id") - - item = KeywordPatentSearchItem( - keyword=keyword, - topic_id=tid, - topic_display_name=display_name, - subfield_name=info.get("subfield"), - field_name=info.get("field"), - relevance_score=1.0, - ) - print(f"Keyword: {keyword}") - print(f"Topic: {display_name} ({tid})") - print(f"Subfield: {info.get('subfield')} | Field: {info.get('field')}") - - lookup = KeywordIpcReverseLookup() - ipc = await lookup.lookup_ipc_codes([item]) - print(f"\nIPC matches ({len(ipc)}):") - for match in ipc[:20]: - print( - f" {match.ipc_symbol:14} score={match.match_score:.3f} " - f"type={match.match_type}" - ) - - terms = _patent_search_terms(ipc) - print(f"\nPatent search terms ({len(terms)}): {terms}") - - response = await get_patents_by_keywords(PatentsByKeywordsRequest(keywords=[item])) - print(f"\nPatents returned: {response.patent_count}") - for entry in response.patents[:10]: - patent = entry.patent - title = (patent.title or "")[:60] - print( - f" score={entry.match_score:.3f} {patent.patent_id} " - f"ipc={entry.matched_ipc_symbols} | {title}" - ) - if patent.ipc: - print(f" raw ipc: {patent.ipc[:2]}") - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("keyword", default="Medizin", nargs="?") - parser.add_argument("--topic-name", default=None) - parser.add_argument("--topic-id", default=None) - args = parser.parse_args() - asyncio.run(diagnose(args.keyword, args.topic_name, args.topic_id)) - - -if __name__ == "__main__": - main() diff --git a/service/scripts/diagnose_patents_openalex_keywords.py b/service/scripts/diagnose_patents_openalex_keywords.py deleted file mode 100644 index d226739f..00000000 --- a/service/scripts/diagnose_patents_openalex_keywords.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python3 -"""Print IPC/CPC → OpenAlex topic/keyword matches from patents_openalex_keywords.""" -from __future__ import annotations - -import argparse -import asyncio -import sys -from pathlib import Path - -current_dir = Path(__file__).resolve().parent -sys.path.insert(0, str(current_dir.parent / "src" / "main")) - -from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient -from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol - -DEFAULT_SYMBOLS = ("A", "A61", "A61B", "G01N", "C12N", "H04L") - - -def _print_match_block(title: str, matches: list[dict]) -> None: - print(f" {title}:") - if not matches: - print(" (none)") - return - for item in matches: - if "keyword" in item: - label = item.get("keyword") - topic = item.get("topic_display_name") or item.get("topic_id") - print( - f" #{item.get('rank')} {label} " - f"[topic={topic}, score={item.get('match_score')}]" - ) - else: - label = item.get("topic_display_name") or item.get("topic_id") - print(f" #{item.get('rank')} {label} (score={item.get('match_score')})") - - -async def diagnose_symbol(client: PatentsOpenAlexKeywordsClient, symbol: str) -> None: - normalized = normalize_symbol(symbol) - print(f"\n{'=' * 70}") - print(f"IPC/CPC symbol: {normalized}") - - doc = await client.lookup_symbol(normalized) - if doc: - print(f"Matched level: {doc.get('ipc_level')}") - print(f"IPC label: {doc.get('ipc_label')}") - _print_match_block("Topic matches", doc.get("topic_matches") or []) - _print_match_block("Keyword matches", doc.get("keyword_matches") or []) - return - - subclass = infer_subclass(normalized) - for level, candidate in ( - ("subgroup", normalized), - ("group", normalized), - ("subclass", subclass), - ("class", normalized[:3] if len(normalized) >= 3 else None), - ("section", normalized[:1] if normalized else None), - ): - if not candidate: - continue - doc = await client.lookup(level, candidate) - if doc: - print(f"Matched level: {doc.get('ipc_level')} (via fallback lookup)") - print(f"IPC label: {doc.get('ipc_label')}") - _print_match_block("Topic matches", doc.get("topic_matches") or []) - _print_match_block("Keyword matches", doc.get("keyword_matches") or []) - return - - print(" No mapping found in patents_openalex_keywords.") - - -async def main() -> None: - parser = argparse.ArgumentParser( - description="Diagnose IPC/CPC matches in patents_openalex_keywords.", - ) - parser.add_argument( - "symbols", - nargs="*", - default=list(DEFAULT_SYMBOLS), - help="IPC/CPC symbols to inspect", - ) - args = parser.parse_args() - - client = PatentsOpenAlexKeywordsClient() - for symbol in args.symbols: - await diagnose_symbol(client, symbol) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/service/src/data/ipc_openalex_topic_mapping.json b/service/src/data/ipc_openalex_topic_mapping.json deleted file mode 100644 index 0d405a23..00000000 --- a/service/src/data/ipc_openalex_topic_mapping.json +++ /dev/null @@ -1,2962 +0,0 @@ -{ - "section": { - "C": { - "topic_id": "https://openalex.org/T14184", - "topic_display_name": "Metallurgy and Material Science", - "ipc_label": "CHEMISTRY; METALLURGY", - "match_score": 1.0 - }, - "D": { - "topic_id": "https://openalex.org/T12514", - "topic_display_name": "Fashion and Cultural Textiles", - "ipc_label": "TEXTILES; PAPER", - "match_score": 0.5 - }, - "E": { - "topic_id": "https://openalex.org/T11777", - "topic_display_name": "Fixed Point Theorems Analysis", - "ipc_label": "FIXED CONSTRUCTIONS", - "match_score": 0.5 - }, - "F": { - "topic_id": "https://openalex.org/T12907", - "topic_display_name": "Mechanical Engineering and Vibrations Research", - "ipc_label": "MECHANICAL ENGINEERING; LIGHTING; HEATING; WEAPONS; BLASTING", - "match_score": 0.604 - }, - "G": { - "topic_id": "https://openalex.org/T12836", - "topic_display_name": "History and Developments in Astronomy", - "ipc_label": "PHYSICS", - "match_score": 1.0 - }, - "H": { - "topic_id": "https://openalex.org/T13429", - "topic_display_name": "Electricity Theft Detection Techniques", - "ipc_label": "ELECTRICITY", - "match_score": 1.0 - }, - "A": { - "topic_id": "https://openalex.org/T13694", - "topic_display_name": "Immigration Law and Human Rights", - "ipc_label": "HUMAN NECESSITIES", - "match_score": 0.6 - }, - "B": { - "topic_id": "https://openalex.org/T12659", - "topic_display_name": "Innovation Diffusion and Forecasting", - "ipc_label": "PERFORMING OPERATIONS; TRANSPORTING", - "match_score": 0.507 - } - }, - "class": { - "A01D": { - "topic_id": "https://openalex.org/T13896", - "topic_display_name": "Health Services Management and Policy", - "ipc_label": "HARVESTINGMOWING", - "match_score": 0.412 - }, - "A01H": { - "topic_id": "https://openalex.org/T10442", - "topic_display_name": "Knee injuries and reconstruction techniques", - "ipc_label": "NEW PLANTS OR NON-TRANSGENIC PROCESSES FOR OBTAINING THEMPLANT REPRODUCTION BY TISSUE CULTURE TECHNIQUES", - "match_score": 0.435 - }, - "A01J": { - "topic_id": "https://openalex.org/T11386", - "topic_display_name": "Bee Products Chemical Analysis", - "ipc_label": "MANUFACTURE OF DAIRY PRODUCTS for chemical matters, see subclass A23C", - "match_score": 0.465 - }, - "A01L": { - "topic_id": "https://openalex.org/T11905", - "topic_display_name": "Veterinary Pharmacology and Anesthesia", - "ipc_label": "SHOEING OF ANIMALS", - "match_score": 0.581 - }, - "A01P": { - "topic_id": "https://openalex.org/T14099", - "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", - "ipc_label": "BIOCIDAL, PEST REPELLANT, PEST ATTRACTANT OR PLANT GROWTH REGULATORY ACTIVITY OF CHEMICAL COMPOUNDS OR PREPARATIONS", - "match_score": 0.386 - }, - "A21C": { - "topic_id": "https://openalex.org/T12282", - "topic_display_name": "Mineral Processing and Grinding", - "ipc_label": "MACHINES OR EQUIPMENT FOR MAKING OR PROCESSING DOUGHSHANDLING BAKED ARTICLES MADE FROM DOUGH", - "match_score": 0.39 - }, - "A22B": { - "topic_id": "https://openalex.org/T13366", - "topic_display_name": "Accounting Theory and Financial Reporting", - "ipc_label": "SLAUGHTERING", - "match_score": 0.545 - }, - "A23K": { - "topic_id": "https://openalex.org/T12181", - "topic_display_name": "Agricultural and Biological Research", - "ipc_label": "FODDER", - "match_score": 0.444 - }, - "A23Y": { - "topic_id": "https://openalex.org/T12388", - "topic_display_name": "Identification and Quantification in Food", - "ipc_label": "INDEXING SCHEME RELATING TO LACTIC OR PROPIONIC ACID BACTERIA USED IN FOODSTUFFS OR FOOD PREPARATION", - "match_score": 0.369 - }, - "A24C": { - "topic_id": "https://openalex.org/T13832", - "topic_display_name": "Advanced Decision-Making Techniques", - "ipc_label": "MACHINES FOR MAKING CIGARS OR CIGARETTES", - "match_score": 0.475 - }, - "A41B": { - "topic_id": "https://openalex.org/T13368", - "topic_display_name": "University Challenges and Reforms", - "ipc_label": "SHIRTSUNDERWEARBABY LINENHANDKERCHIEFS", - "match_score": 0.451 - }, - "A41C": { - "topic_id": "https://openalex.org/T14190", - "topic_display_name": "Military history and social perspectives", - "ipc_label": "CORSETSBRASSIERES", - "match_score": 0.485 - }, - "A41D": { - "topic_id": "https://openalex.org/T13272", - "topic_display_name": "Psychological Treatments and Assessments", - "ipc_label": "OUTERWEARPROTECTIVE GARMENTSACCESSORIES", - "match_score": 0.43 - }, - "A41F": { - "topic_id": "https://openalex.org/T13129", - "topic_display_name": "Material Properties and Applications", - "ipc_label": "GARMENT FASTENINGSSUSPENDERS", - "match_score": 0.491 - }, - "A41G": { - "topic_id": "https://openalex.org/T13734", - "topic_display_name": "Advanced Computational Techniques and Applications", - "ipc_label": "ARTIFICIAL FLOWERSWIGSMASKSFEATHERS", - "match_score": 0.552 - }, - "A42C": { - "topic_id": "https://openalex.org/T11159", - "topic_display_name": "Manufacturing Process and Optimization", - "ipc_label": "MANUFACTURING OR TRIMMING HEAD COVERINGS, e.g. HATS", - "match_score": 0.494 - }, - "A43B": { - "topic_id": "https://openalex.org/T13232", - "topic_display_name": "Laser-Ablation Synthesis of Nanoparticles", - "ipc_label": "CHARACTERISTIC FEATURES OF FOOTWEARPARTS OF FOOTWEAR", - "match_score": 0.387 - }, - "A43C": { - "topic_id": "https://openalex.org/T13288", - "topic_display_name": "Banking, Crisis Management, COVID-19 Impact", - "ipc_label": "FASTENINGS OR ATTACHMENTS OF FOOTWEARLACES IN GENERAL", - "match_score": 0.375 - }, - "A43D": { - "topic_id": "https://openalex.org/T13290", - "topic_display_name": "Diverse Industrial Engineering Technologies", - "ipc_label": "MACHINES, TOOLS, EQUIPMENT OR METHODS FOR MANUFACTURING OR REPAIRING FOOTWEAR", - "match_score": 0.462 - }, - "A44C": { - "topic_id": "https://openalex.org/T12607", - "topic_display_name": "Personal Information Management and User Behavior", - "ipc_label": "PERSONAL ADORNMENTS, e.g. JEWELLERYCOINS", - "match_score": 0.449 - }, - "A44D": { - "topic_id": "https://openalex.org/T11334", - "topic_display_name": "Psychosomatic Disorders and Their Treatments", - "ipc_label": "INDEXING SCHEME RELATING TO BUTTONS, PINS, BUCKLES OR SLIDE FASTENERS, AND TO JEWELLERY, BRACELETS OR OTHER PERSONAL ADORNMENTS", - "match_score": 0.374 - }, - "A45C": { - "topic_id": "https://openalex.org/T10413", - "topic_display_name": "High-pressure geophysics and materials", - "ipc_label": "PURSESLUGGAGEHAND CARRIED BAGS", - "match_score": 0.471 - }, - "A45F": { - "topic_id": "https://openalex.org/T11867", - "topic_display_name": "Traumatic Ocular and Foreign Body Injuries", - "ipc_label": "TRAVELLING OR CAMP EQUIPMENT: SACKS OR PACKS CARRIED ON THE BODY", - "match_score": 0.358 - }, - "A46B": { - "topic_id": "https://openalex.org/T13398", - "topic_display_name": "Data Analysis with R", - "ipc_label": "BRUSHES handles not integral with brushware B25G", - "match_score": 0.353 - }, - "A46D": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "MANUFACTURE OF BRUSHES", - "match_score": 0.455 - }, - "A47B": { - "topic_id": "https://openalex.org/T14133", - "topic_display_name": "Border Security and International Relations", - "ipc_label": "TABLESDESKSOFFICE FURNITURECABINETSDRAWERSGENERAL DETAILS OF FURNITURE furniture jointing F16B", - "match_score": 0.35 - }, - "A47C": { - "topic_id": "https://openalex.org/T10495", - "topic_display_name": "Catalysts for Methane Reforming", - "ipc_label": "CHAIRS seats specially adapted for vehicles B60N2/00SOFASBEDS upholstery in general B68G", - "match_score": 0.353 - }, - "A47G": { - "topic_id": "https://openalex.org/T14160", - "topic_display_name": "Water management and technologies", - "ipc_label": "HOUSEHOLD OR TABLE EQUIPMENT book-ends A47B5/00; knives B26B", - "match_score": 0.366 - }, - "A47J": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "KITCHEN EQUIPMENTCOFFEE MILLSSPICE MILLSAPPARATUS FOR MAKING BEVERAGES", - "match_score": 0.378 - }, - "A61D": { - "topic_id": "https://openalex.org/T14236", - "topic_display_name": "Educational Tools and Methods", - "ipc_label": "VETERINARY INSTRUMENTS, IMPLEMENTS, TOOLS, OR METHODS", - "match_score": 0.512 - }, - "A61P": { - "topic_id": "https://openalex.org/T12685", - "topic_display_name": "Phytochemical compounds biological activities", - "ipc_label": "SPECIFIC THERAPEUTIC ACTIVITY OF CHEMICAL COMPOUNDS OR MEDICINAL PREPARATIONS", - "match_score": 0.525 - }, - "A61Q": { - "topic_id": "https://openalex.org/T10576", - "topic_display_name": "Opioid Use Disorder Treatment", - "ipc_label": "SPECIFIC USE OF COSMETICS OR SIMILAR TOILETRY PREPARATIONS", - "match_score": 0.437 - }, - "A62D": { - "topic_id": "https://openalex.org/T11802", - "topic_display_name": "Chemical Looping and Thermochemical Processes", - "ipc_label": "CHEMICAL MEANS FOR EXTINGUISHING FIRES OR FOR COMBATING OR PROTECTING AGAINST HARMFUL CHEMICAL AGENTSCHEMICAL MATERIALS FOR USE IN BREATHING APPARATUS", - "match_score": 0.369 - }, - "A63H": { - "topic_id": "https://openalex.org/T12105", - "topic_display_name": "Hygrothermal properties of building materials", - "ipc_label": "TOYS, e.g. TOPS, DOLLS, HOOPS OR BUILDING BLOCKS", - "match_score": 0.409 - }, - "A99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "B01B": { - "topic_id": "https://openalex.org/T11900", - "topic_display_name": "Fungal Plant Pathogen Control", - "ipc_label": "BOILINGBOILING APPARATUS ; EVAPORATION; EVAPORATION APPARATUS", - "match_score": 0.381 - }, - "B01J": { - "topic_id": "https://openalex.org/T13104", - "topic_display_name": "Chemical and Physical Properties of Materials", - "ipc_label": "CHEMICAL OR PHYSICAL PROCESSES, e.g. CATALYSIS OR COLLOID CHEMISTRYTHEIR RELEVANT APPARATUS", - "match_score": 0.471 - }, - "B01L": { - "topic_id": "https://openalex.org/T13104", - "topic_display_name": "Chemical and Physical Properties of Materials", - "ipc_label": "CHEMICAL OR PHYSICAL LABORATORY APPARATUS FOR GENERAL USE", - "match_score": 0.549 - }, - "B03B": { - "topic_id": "https://openalex.org/T11808", - "topic_display_name": "Superconducting Materials and Applications", - "ipc_label": "SEPARATING SOLID MATERIALS USING LIQUIDS OR USING PNEUMATIC TABLES OR JIGS", - "match_score": 0.448 - }, - "B09B": { - "topic_id": "https://openalex.org/T11108", - "topic_display_name": "Municipal Solid Waste Management", - "ipc_label": "DISPOSAL OF SOLID WASTE", - "match_score": 0.667 - }, - "B21G": { - "topic_id": "https://openalex.org/T10377", - "topic_display_name": "Metal and Thin Film Mechanics", - "ipc_label": "MAKING NEEDLES, PINS OR NAILS OF METAL", - "match_score": 0.4 - }, - "B22C": { - "topic_id": "https://openalex.org/T11853", - "topic_display_name": "Semiconductor materials and interfaces", - "ipc_label": "FOUNDRY MOULDING moulding refractory materials in general B28B", - "match_score": 0.48 - }, - "B23B": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "TURNINGBORING arrangements for copying or controlling B23Q", - "match_score": 0.424 - }, - "B24C": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "ABRASIVE OR RELATED BLASTING WITH PARTICULATE MATERIAL", - "match_score": 0.469 - }, - "B25H": { - "topic_id": "https://openalex.org/T10488", - "topic_display_name": "Nanocomposite Films for Food Packaging", - "ipc_label": "WORKSHOP EQUIPMENT, e.g. FOR MARKING-OUT WORKSTORAGE MEANS FOR WORKSHOPS storing or packaging B65", - "match_score": 0.356 - }, - "B27H": { - "topic_id": "https://openalex.org/T14076", - "topic_display_name": "Material Properties and Failure Mechanisms", - "ipc_label": "BENDING WOOD OR SIMILAR MATERIALCOOPERAGEMAKING WHEELS FROM WOOD OR SIMILAR MATERIAL", - "match_score": 0.381 - }, - "B27J": { - "topic_id": "https://openalex.org/T10219", - "topic_display_name": "Mechanical Behavior of Composites", - "ipc_label": "MECHANICAL WORKING OF CANE, CORK, OR SIMILAR MATERIALS", - "match_score": 0.575 - }, - "B28D": { - "topic_id": "https://openalex.org/T10811", - "topic_display_name": "Hydrogen Storage and Materials", - "ipc_label": "WORKING STONE OR STONE-LIKE MATERIALS", - "match_score": 0.567 - }, - "B29L": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS B29C, RELATING TO PARTICULAR ARTICLES", - "match_score": 0.393 - }, - "B41F": { - "topic_id": "https://openalex.org/T11523", - "topic_display_name": "Nanomaterials and Printing Technologies", - "ipc_label": "PRINTING MACHINES OR PRESSES manifolding devices or office printing machines B41L", - "match_score": 0.383 - }, - "B41P": { - "topic_id": "https://openalex.org/T13557", - "topic_display_name": "Environmental and sustainability education", - "ipc_label": "INDEXING SCHEME RELATING TO PRINTING, LINING MACHINES, TYPEWRITERS, AND TO STAMPS", - "match_score": 0.42 - }, - "B42P": { - "topic_id": "https://openalex.org/T11877", - "topic_display_name": "Iron oxide chemistry and applications", - "ipc_label": "INDEXING SCHEME RELATING TO BOOKS, FILING APPLIANCES OR THE LIKE", - "match_score": 0.416 - }, - "B44F": { - "topic_id": "https://openalex.org/T12174", - "topic_display_name": "Hospital Admissions and Outcomes", - "ipc_label": "SPECIAL DESIGNS OR PICTURES", - "match_score": 0.542 - }, - "B60C": { - "topic_id": "https://openalex.org/T12641", - "topic_display_name": "Historical and socio-economic studies of Spain and related regions", - "ipc_label": "VEHICLE TYRESTYRE INFLATIONTYRE CHANGINGCONNECTING VALVES TO INFLATABLE ELASTIC BODIES IN GENERALDEVICES OR ARRANGEMENTS RELATED TO TYRES", - "match_score": 0.384 - }, - "B60D": { - "topic_id": "https://openalex.org/T10829", - "topic_display_name": "Interconnection Networks and Systems", - "ipc_label": "VEHICLE CONNECTIONS components of brake systems B60T17/04", - "match_score": 0.473 - }, - "B60F": { - "topic_id": "https://openalex.org/T14022", - "topic_display_name": "Cultural and Religious Practices in Indonesia", - "ipc_label": "VEHICLES FOR USE BOTH ON RAIL AND ON ROADAMPHIBIOUS OR LIKE VEHICLESCONVERTIBLE VEHICLES air-cushion vehicles B60V", - "match_score": 0.377 - }, - "B60G": { - "topic_id": "https://openalex.org/T10805", - "topic_display_name": "Vehicle Dynamics and Control Systems", - "ipc_label": "VEHICLE SUSPENSION ARRANGEMENTS air-cushion vehicles B60V; cycle suspensions B62K25/00", - "match_score": 0.361 - }, - "B60H": { - "topic_id": "https://openalex.org/T10558", - "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", - "ipc_label": "ARRANGEMENTS OF HEATING, COOLING, VENTILATING OR OTHER AIR-TREATING DEVICES SPECIALLY ADAPTED FOR PASSENGER OR GOODS SPACES OF VEHICLES", - "match_score": 0.366 - }, - "B60Q": { - "topic_id": "https://openalex.org/T10558", - "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", - "ipc_label": "ARRANGEMENT OF SIGNALLING OR LIGHTING DEVICES, THE MOUNTING OR SUPPORTING THEREOF OR CIRCUITS THEREFOR, FOR VEHICLES IN GENERAL", - "match_score": 0.415 - }, - "B60R": { - "topic_id": "https://openalex.org/T12707", - "topic_display_name": "Vehicle License Plate Recognition", - "ipc_label": "VEHICLES, VEHICLE FITTINGS, OR VEHICLE PARTS, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.381 - }, - "B60V": { - "topic_id": "https://openalex.org/T11002", - "topic_display_name": "Indoor Air Quality and Microbial Exposure", - "ipc_label": "AIR-CUSHION VEHICLES", - "match_score": 0.393 - }, - "B60Y": { - "topic_id": "https://openalex.org/T12898", - "topic_display_name": "Induction Heating and Inverter Technology", - "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS CROSS-CUTTING VEHICLE TECHNOLOGY", - "match_score": 0.569 - }, - "B61D": { - "topic_id": "https://openalex.org/T12271", - "topic_display_name": "Renewable energy and sustainable power systems", - "ipc_label": "BODY DETAILS OR KINDS OF RAILWAY VEHICLES vehicles in general B60; adaptation of vehicles to special systems B61B; underframes B61F", - "match_score": 0.35 - }, - "B61G": { - "topic_id": "https://openalex.org/T14049", - "topic_display_name": "Plant and Fungal Species Descriptions", - "ipc_label": "COUPLINGSDRAUGHT AND BUFFING APPLIANCES vehicle connections in general B60D", - "match_score": 0.446 - }, - "B61J": { - "topic_id": "https://openalex.org/T10757", - "topic_display_name": "Geographic Information Systems Studies", - "ipc_label": "SHIFTING OR SHUNTING OF RAIL VEHICLES shifting vehicles in general B60S; marshalling systems B61B", - "match_score": 0.37 - }, - "B62C": { - "topic_id": "https://openalex.org/T13551", - "topic_display_name": "Biochemical effects in animals", - "ipc_label": "VEHICLES DRAWN BY ANIMALS", - "match_score": 0.582 - }, - "B63J": { - "topic_id": "https://openalex.org/T11427", - "topic_display_name": "Elbow and Forearm Trauma Treatment", - "ipc_label": "AUXILIARIES ON VESSELS", - "match_score": 0.444 - }, - "B64B": { - "topic_id": "https://openalex.org/T12916", - "topic_display_name": "COVID-19 impact on air quality", - "ipc_label": "LIGHTER-THAN AIR AIRCRAFT", - "match_score": 0.4 - }, - "B64C": { - "topic_id": "https://openalex.org/T10647", - "topic_display_name": "Coastal and Marine Dynamics", - "ipc_label": "AEROPLANESHELICOPTERS", - "match_score": 0.49 - }, - "B64U": { - "topic_id": "https://openalex.org/T11192", - "topic_display_name": "Underwater Vehicles and Communication Systems", - "ipc_label": "UNMANNED AERIAL VEHICLES [UAV]EQUIPMENT THEREFOR", - "match_score": 0.43 - }, - "B65H": { - "topic_id": "https://openalex.org/T13917", - "topic_display_name": "Engineering and Material Science Research", - "ipc_label": "HANDLING THIN OR FILAMENTARY MATERIAL, e.g. SHEETS, WEBS, CABLES", - "match_score": 0.419 - }, - "B68B": { - "topic_id": "https://openalex.org/T12617", - "topic_display_name": "Energy, Environment, and Transportation Policies", - "ipc_label": "HARNESSDEVICES USED IN CONNECTION THEREWITHWHIPS OR THE LIKE", - "match_score": 0.389 - }, - "B68C": { - "topic_id": "https://openalex.org/T13896", - "topic_display_name": "Health Services Management and Policy", - "ipc_label": "SADDLESSTIRRUPS", - "match_score": 0.424 - }, - "B81B": { - "topic_id": "https://openalex.org/T12111", - "topic_display_name": "Industrial Vision Systems and Defect Detection", - "ipc_label": "MICROSTRUCTURAL DEVICES OR SYSTEMS, e.g. MICROMECHANICAL DEVICES piezo-electric, electrostrictive or magnetostrictive elements per se H10N30/00", - "match_score": 0.37 - }, - "B82Y": { - "topic_id": "https://openalex.org/T11169", - "topic_display_name": "Silicon Nanostructures and Photoluminescence", - "ipc_label": "SPECIFIC USES OR APPLICATIONS OF NANOSTRUCTURESMEASUREMENT OR ANALYSIS OF NANOSTRUCTURESMANUFACTURE OR TREATMENT OF NANOSTRUCTURES", - "match_score": 0.402 - }, - "B99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "C01B": { - "topic_id": "https://openalex.org/T12458", - "topic_display_name": "Organometallic Compounds Synthesis and Characterization", - "ipc_label": "NON-METALLIC ELEMENTSCOMPOUNDS THEREOF; METALLOIDS OR COMPOUNDS THEREOF NOT COVERED BY SUBCLASS C01C", - "match_score": 0.4 - }, - "C01P": { - "topic_id": "https://openalex.org/T12410", - "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", - "ipc_label": "INDEXING SCHEME RELATING TO STRUCTURAL AND PHYSICAL ASPECTS OF SOLID INORGANIC COMPOUNDS", - "match_score": 0.658 - }, - "C03B": { - "topic_id": "https://openalex.org/T10705", - "topic_display_name": "Additive Manufacturing Materials and Processes", - "ipc_label": "MANUFACTURE, SHAPING, OR SUPPLEMENTARY PROCESSES", - "match_score": 0.574 - }, - "C05B": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "PHOSPHATIC FERTILISERS", - "match_score": 0.5 - }, - "C05C": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "NITROGENOUS FERTILISERS", - "match_score": 0.444 - }, - "C05D": { - "topic_id": "https://openalex.org/T10973", - "topic_display_name": "Radioactive element chemistry and processing", - "ipc_label": "INORGANIC FERTILISERS NOT COVERED BY SUBCLASSES C05B, C05CFERTILISERS PRODUCING CARBON DIOXIDE", - "match_score": 0.362 - }, - "C06F": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "MATCHESMANUFACTURE OF MATCHES", - "match_score": 0.588 - }, - "C07B": { - "topic_id": "https://openalex.org/T14099", - "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", - "ipc_label": "GENERAL METHODS OF ORGANIC CHEMISTRYAPPARATUS THEREFOR preparation of carboxylic acid esters by telomerisation C07C67/47; telomerisation C08F", - "match_score": 0.355 - }, - "C07C": { - "topic_id": "https://openalex.org/T13208", - "topic_display_name": "Synthesis of heterocyclic compounds", - "ipc_label": "ACYCLIC OR CARBOCYCLIC COMPOUNDS", - "match_score": 0.657 - }, - "C07D": { - "topic_id": "https://openalex.org/T13208", - "topic_display_name": "Synthesis of heterocyclic compounds", - "ipc_label": "HETEROCYCLIC COMPOUNDS macromolecular compounds C08", - "match_score": 0.512 - }, - "C07G": { - "topic_id": "https://openalex.org/T12055", - "topic_display_name": "Boron Compounds in Chemistry", - "ipc_label": "COMPOUNDS OF UNKNOWN CONSTITUTION", - "match_score": 0.492 - }, - "C07J": { - "topic_id": "https://openalex.org/T10310", - "topic_display_name": "Corrosion Behavior and Inhibition", - "ipc_label": "STEROIDS seco-steroids C07C", - "match_score": 0.455 - }, - "C08C": { - "topic_id": "https://openalex.org/T13037", - "topic_display_name": "Piperaceae Chemical and Biological Studies", - "ipc_label": "TREATMENT OR CHEMICAL MODIFICATION OF RUBBERS", - "match_score": 0.506 - }, - "C08F": { - "topic_id": "https://openalex.org/T13239", - "topic_display_name": "Phosphorus compounds and reactions", - "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED BY REACTIONS ONLY INVOLVING CARBON-TO-CARBON UNSATURATED BONDS", - "match_score": 0.4 - }, - "C08G": { - "topic_id": "https://openalex.org/T14459", - "topic_display_name": "Synthesis and Reactions of Organic Compounds", - "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED OTHERWISE THAN BY REACTIONS ONLY INVOLVING UNSATURATED CARBON-TO-CARBON BONDS", - "match_score": 0.387 - }, - "C09F": { - "topic_id": "https://openalex.org/T11823", - "topic_display_name": "Natural Resources and Economic Development", - "ipc_label": "NATURAL RESINSFRENCH POLISHDRYING-OILSDRIERS (SICCATIVES)TURPENTINE", - "match_score": 0.422 - }, - "C09G": { - "topic_id": "https://openalex.org/T12638", - "topic_display_name": "Pomegranate: compositions and health benefits", - "ipc_label": "POLISHING COMPOSITIONS French polish C09F11/00SKI WAXES", - "match_score": 0.42 - }, - "C09H": { - "topic_id": "https://openalex.org/T14032", - "topic_display_name": "History and International Relations", - "ipc_label": "PREPARATION OF GLUE OR GELATINE", - "match_score": 0.485 - }, - "C09K": { - "topic_id": "https://openalex.org/T10245", - "topic_display_name": "Metamaterials and Metasurfaces Applications", - "ipc_label": "MATERIALS FOR MISCELLANEOUS APPLICATIONS, NOT PROVIDED FOR ELSEWHERE", - "match_score": 0.523 - }, - "C10F": { - "topic_id": "https://openalex.org/T10650", - "topic_display_name": "Food Drying and Modeling", - "ipc_label": "DRYING OR WORKING-UP OF PEAT", - "match_score": 0.423 - }, - "C10H": { - "topic_id": "https://openalex.org/T12931", - "topic_display_name": "Educational Methods and Outcomes", - "ipc_label": "PRODUCTION OF ACETYLENE BY WET METHODS purification of acetylene C07C7/00", - "match_score": 0.457 - }, - "C10K": { - "topic_id": "https://openalex.org/T11848", - "topic_display_name": "Heme Oxygenase-1 and Carbon Monoxide", - "ipc_label": "PURIFYING OR MODIFYING THE CHEMICAL COMPOSITION OF COMBUSTIBLE GASES CONTAINING CARBON MONOXIDE", - "match_score": 0.412 - }, - "C10N": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS C10M RELATING TO LUBRICATING COMPOSITIONS", - "match_score": 0.397 - }, - "C11D": { - "topic_id": "https://openalex.org/T11869", - "topic_display_name": "Per- and polyfluoroalkyl substances research", - "ipc_label": "DETERGENT COMPOSITIONSUSE OF SINGLE SUBSTANCES AS DETERGENTSSOAP OR SOAP-MAKINGRESIN SOAPSRECOVERY OF GLYCEROL", - "match_score": 0.351 - }, - "C12J": { - "topic_id": "https://openalex.org/T12008", - "topic_display_name": "Solar-Powered Water Purification Methods", - "ipc_label": "VINEGARPREPARATION OR PURIFICATION THEREOF", - "match_score": 0.61 - }, - "C12R": { - "topic_id": "https://openalex.org/T10685", - "topic_display_name": "Viral-associated cancers and disorders", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES C12C - C12Q, RELATING TO MICROORGANISMS", - "match_score": 0.367 - }, - "C12Y": { - "topic_id": "https://openalex.org/T12770", - "topic_display_name": "Amino Acid Enzymes and Metabolism", - "ipc_label": "ENZYMES", - "match_score": 1.0 - }, - "C13B": { - "topic_id": "https://openalex.org/T12410", - "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", - "ipc_label": "PRODUCTION OF SUCROSEAPPARATUS SPECIALLY ADAPTED THEREFOR chemically synthesised sugars or sugar derivatives C07H; fermentation or enzyme-using processes for preparing compounds containing saccharide radicals C12P19/00", - "match_score": 0.351 - }, - "C21B": { - "topic_id": "https://openalex.org/T12301", - "topic_display_name": "Facial Nerve Paralysis Treatment and Research", - "ipc_label": "MANUFACTURE OF IRON OR STEEL preliminary treatment of ferrous ores or scrap C22B1/00; electric heating H05B", - "match_score": 0.368 - }, - "C22B": { - "topic_id": "https://openalex.org/T13652", - "topic_display_name": "Education and Social Development in Ukraine", - "ipc_label": "PRODUCTION AND REFINING OF METALS electrolytic C25PRETREATMENT OF RAW MATERIALS", - "match_score": 0.475 - }, - "C22C": { - "topic_id": "https://openalex.org/T11453", - "topic_display_name": "Diagnosis and Treatment of Venous Diseases", - "ipc_label": "ALLOYS flints C06C15/00; treatment of alloys C21D, C22F", - "match_score": 0.474 - }, - "C23D": { - "topic_id": "https://openalex.org/T13463", - "topic_display_name": "Nanoporous metals and alloys", - "ipc_label": "ENAMELLING OF, OR APPLYING A VITREOUS LAYER TO, METALS", - "match_score": 0.39 - }, - "C23G": { - "topic_id": "https://openalex.org/T14068", - "topic_display_name": "Organic and Inorganic Chemical Reactions", - "ipc_label": "CLEANING OR DE-GREASING OF METALLIC MATERIAL BY CHEMICAL METHODS OTHER THAN ELECTROLYSIS", - "match_score": 0.438 - }, - "C25C": { - "topic_id": "https://openalex.org/T10962", - "topic_display_name": "Thermodynamic properties of mixtures", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC PRODUCTION, RECOVERY OR REFINING OF METALSAPPARATUS THEREFOR", - "match_score": 0.378 - }, - "C25D": { - "topic_id": "https://openalex.org/T14382", - "topic_display_name": "Electrophoretic Deposition in Materials Science", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC OR ELECTROPHORETIC PRODUCTION OF COATINGSELECTROFORMINGAPPARATUS THEREFOR", - "match_score": 0.424 - }, - "C25F": { - "topic_id": "https://openalex.org/T11025", - "topic_display_name": "Nonlinear Optical Materials Research", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC REMOVAL OF MATERIALS FROM OBJECTSAPPARATUS THEREFOR", - "match_score": 0.458 - }, - "C99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "D01D": { - "topic_id": "https://openalex.org/T11416", - "topic_display_name": "Numerical methods for differential equations", - "ipc_label": "MECHANICAL METHODS OR APPARATUS IN THE MANUFACTURE OF ARTIFICIAL FILAMENTS, THREADS, FIBRES, BRISTLES OR RIBBONS", - "match_score": 0.397 - }, - "D02G": { - "topic_id": "https://openalex.org/T14192", - "topic_display_name": "Literature, Film, and Journalism Analysis", - "ipc_label": "CRIMPING OR CURLING FIBRES, FILAMENTS, THREADS, OR YARNSYARNS OR THREADS", - "match_score": 0.389 - }, - "D02H": { - "topic_id": "https://openalex.org/T13523", - "topic_display_name": "Mathematics, Computing, and Information Processing", - "ipc_label": "WARPING, BEAMING OR LEASING", - "match_score": 0.468 - }, - "D03C": { - "topic_id": "https://openalex.org/T12490", - "topic_display_name": "Software Engineering and Design Patterns", - "ipc_label": "SHEDDING MECHANISMSPATTERN CARDS OR CHAINSPUNCHING OF CARDSDESIGNING PATTERNS", - "match_score": 0.41 - }, - "D03D": { - "topic_id": "https://openalex.org/T13880", - "topic_display_name": "Innovative Education Methods and Tools", - "ipc_label": "WOVEN FABRICSMETHODS OF WEAVINGLOOMS", - "match_score": 0.459 - }, - "D03J": { - "topic_id": "https://openalex.org/T10262", - "topic_display_name": "Microwave Engineering and Waveguides", - "ipc_label": "AUXILIARY WEAVING APPARATUSWEAVERS' TOOLSSHUTTLES", - "match_score": 0.4 - }, - "D04B": { - "topic_id": "https://openalex.org/T13366", - "topic_display_name": "Accounting Theory and Financial Reporting", - "ipc_label": "KNITTING", - "match_score": 0.556 - }, - "D05C": { - "topic_id": "https://openalex.org/T13583", - "topic_display_name": "Jury Decision Making Processes", - "ipc_label": "EMBROIDERINGTUFTING making non-woven fabrics D04H; sewing D05B", - "match_score": 0.391 - }, - "D05D": { - "topic_id": "https://openalex.org/T14497", - "topic_display_name": "Social Issues and Policies in Latin America", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES D05B AND D05C, RELATING TO SEWING, EMBROIDERING AND TUFTING", - "match_score": 0.4 - }, - "D06C": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "FINISHING, DRESSING, TENTERING OR STRETCHING TEXTILE FABRICS", - "match_score": 0.484 - }, - "D06F": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "LAUNDERING, DRYING, IRONING, PRESSING OR FOLDING TEXTILE ARTICLES", - "match_score": 0.44 - }, - "D06H": { - "topic_id": "https://openalex.org/T11948", - "topic_display_name": "Machine Learning in Materials Science", - "ipc_label": "MARKING, INSPECTING, SEAMING OR SEVERING TEXTILE MATERIALS seaming by sewing D05B", - "match_score": 0.475 - }, - "D06P": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "DYEING OR PRINTING TEXTILESDYEING LEATHER, FURS OR SOLID MACROMOLECULAR SUBSTANCES IN ANY FORM", - "match_score": 0.372 - }, - "D10B": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBLASSES OF SECTION D, RELATING TO TEXTILES", - "match_score": 0.4 - }, - "D21B": { - "topic_id": "https://openalex.org/T11485", - "topic_display_name": "Gastrointestinal Tumor Research and Treatment", - "ipc_label": "FIBROUS RAW MATERIALS OR THEIR MECHANICAL TREATMENT", - "match_score": 0.562 - }, - "D21D": { - "topic_id": "https://openalex.org/T11071", - "topic_display_name": "Treatment of Major Depression", - "ipc_label": "TREATMENT OF THE MATERIALS BEFORE PASSING TO THE PAPER-MAKING MACHINE", - "match_score": 0.469 - }, - "D99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "E01F": { - "topic_id": "https://openalex.org/T14390", - "topic_display_name": "Real estate and construction management", - "ipc_label": "ADDITIONAL WORK, SUCH AS EQUIPPING ROADS OR THE CONSTRUCTION OF PLATFORMS, HELICOPTER LANDING STAGES, SIGNS, SNOW FENCES, OR THE LIKE", - "match_score": 0.36 - }, - "E02B": { - "topic_id": "https://openalex.org/T12907", - "topic_display_name": "Mechanical Engineering and Vibrations Research", - "ipc_label": "HYDRAULIC ENGINEERING ship-lifting E02C; dredging E02F", - "match_score": 0.5 - }, - "E02C": { - "topic_id": "https://openalex.org/T13253", - "topic_display_name": "Chemical Reactions and Mechanisms", - "ipc_label": "SHIP-LIFTING DEVICES OR MECHANISMS", - "match_score": 0.567 - }, - "E02D": { - "topic_id": "https://openalex.org/T12233", - "topic_display_name": "Geotechnical Engineering and Underground Structures", - "ipc_label": "FOUNDATIONSEXCAVATIONSEMBANKMENTS specially adapted for hydraulic engineering E02BUNDERGROUND OR UNDERWATER STRUCTURES tunnels, tunnelling, mining E21", - "match_score": 0.408 - }, - "E02F": { - "topic_id": "https://openalex.org/T13027", - "topic_display_name": "Applied Advanced Technologies", - "ipc_label": "DREDGINGSOIL-SHIFTING winning peat E21C49/00", - "match_score": 0.381 - }, - "E03D": { - "topic_id": "https://openalex.org/T14249", - "topic_display_name": "Water Quality Monitoring and Analysis", - "ipc_label": "WATER-CLOSETS OR URINALS WITH FLUSHING DEVICESFLUSHING VALVES THEREFOR", - "match_score": 0.355 - }, - "E03F": { - "topic_id": "https://openalex.org/T13675", - "topic_display_name": "Diffusion Coefficients in Liquids", - "ipc_label": "SEWERSCESSPOOLS", - "match_score": 0.444 - }, - "E05B": { - "topic_id": "https://openalex.org/T10859", - "topic_display_name": "Polymer Surface Interaction Studies", - "ipc_label": "LOCKSACCESSORIES THEREFORHANDCUFFS", - "match_score": 0.452 - }, - "E21C": { - "topic_id": "https://openalex.org/T11933", - "topic_display_name": "Mining and Resource Management", - "ipc_label": "MINING OR QUARRYING", - "match_score": 0.531 - }, - "E21F": { - "topic_id": "https://openalex.org/T10570", - "topic_display_name": "Drug Transport and Resistance Mechanisms", - "ipc_label": "SAFETY DEVICES, TRANSPORT, FILLING-UP, RESCUE, VENTILATION, OR DRAINING IN OR OF MINES OR TUNNELS", - "match_score": 0.38 - }, - "E99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "F01L": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "CYCLICALLY OPERATING VALVES FOR MACHINES OR ENGINES", - "match_score": 0.478 - }, - "F02F": { - "topic_id": "https://openalex.org/T10117", - "topic_display_name": "Advanced Combustion Engine Technologies", - "ipc_label": "CYLINDERS, PISTONS OR CASINGS, FOR COMBUSTION ENGINESARRANGEMENTS OF SEALINGS IN COMBUSTION ENGINES", - "match_score": 0.406 - }, - "F02M": { - "topic_id": "https://openalex.org/T13917", - "topic_display_name": "Engineering and Material Science Research", - "ipc_label": "SUPPLYING COMBUSTION ENGINES IN GENERAL WITH COMBUSTIBLE MIXTURES OR CONSTITUENTS THEREOF", - "match_score": 0.385 - }, - "F02N": { - "topic_id": "https://openalex.org/T10117", - "topic_display_name": "Advanced Combustion Engine Technologies", - "ipc_label": "STARTING OF COMBUSTION ENGINESSTARTING AIDS FOR SUCH ENGINES, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.441 - }, - "F03D": { - "topic_id": "https://openalex.org/T10504", - "topic_display_name": "Sensorless Control of Electric Motors", - "ipc_label": "WIND MOTORS", - "match_score": 0.5 - }, - "F03H": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "PRODUCING A REACTIVE PROPULSIVE THRUST, NOT OTHERWISE PROVIDED FOR from combustion products F02K", - "match_score": 0.35 - }, - "F16C": { - "topic_id": "https://openalex.org/T14144", - "topic_display_name": "Neurological Disease Mechanisms and Treatments", - "ipc_label": "SHAFTSFLEXIBLE SHAFTSELEMENTS OR CRANKSHAFT MECHANISMSROTARY BODIES OTHER THAN GEARING ELEMENTSBEARINGS", - "match_score": 0.376 - }, - "F16D": { - "topic_id": "https://openalex.org/T12240", - "topic_display_name": "Nanomaterials for catalytic reactions", - "ipc_label": "COUPLINGS FOR TRANSMITTING ROTATIONCLUTCHESBRAKES", - "match_score": 0.465 - }, - "F16F": { - "topic_id": "https://openalex.org/T10030", - "topic_display_name": "Electrocatalysts for Energy Conversion", - "ipc_label": "SPRINGSSHOCK-ABSORBERSMEANS FOR DAMPING VIBRATION", - "match_score": 0.437 - }, - "F16H": { - "topic_id": "https://openalex.org/T14252", - "topic_display_name": "Water and Wastewater Treatment", - "ipc_label": "GEARING", - "match_score": 0.667 - }, - "F16J": { - "topic_id": "https://openalex.org/T14353", - "topic_display_name": "Wireless Sensor Networks for Data Analysis", - "ipc_label": "PISTONS specially adapted for dampers F16F9/32CYLINDERSSEALINGS", - "match_score": 0.4 - }, - "F16L": { - "topic_id": "https://openalex.org/T11343", - "topic_display_name": "Power Transformer Diagnostics and Insulation", - "ipc_label": "PIPESJOINTS OR FITTINGS FOR PIPESSUPPORTS FOR PIPES, CABLES OR PROTECTIVE TUBINGMEANS FOR THERMAL INSULATION IN GENERAL", - "match_score": 0.356 - }, - "F16N": { - "topic_id": "https://openalex.org/T14075", - "topic_display_name": "Psychodrama and Leishmaniasis Studies", - "ipc_label": "LUBRICATING", - "match_score": 0.6 - }, - "F16P": { - "topic_id": "https://openalex.org/T11317", - "topic_display_name": "Fire dynamics and safety research", - "ipc_label": "SAFETY DEVICES IN GENERAL; SAFETY DEVICES FOR PRESSES", - "match_score": 0.488 - }, - "F16S": { - "topic_id": "https://openalex.org/T10915", - "topic_display_name": "Trace Elements in Health", - "ipc_label": "CONSTRUCTIONAL ELEMENTS IN GENERALSTRUCTURES BUILT-UP FROM SUCH ELEMENTS, IN GENERAL", - "match_score": 0.389 - }, - "F21L": { - "topic_id": "https://openalex.org/T13000", - "topic_display_name": "World Systems and Global Transformations", - "ipc_label": "LIGHTING DEVICES OR SYSTEMS THEREOF, BEING PORTABLE OR SPECIALLY ADAPTED FOR TRANSPORTATION", - "match_score": 0.427 - }, - "F21W": { - "topic_id": "https://openalex.org/T13257", - "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES F21K, F21L, F21S and F21V, RELATING TO USES OR APPLICATIONS OF LIGHTING DEVICES OR SYSTEMS", - "match_score": 0.383 - }, - "F22G": { - "topic_id": "https://openalex.org/T13960", - "topic_display_name": "Dietetics, Nutrition, and Education", - "ipc_label": "SUPERHEATING OF STEAM steam separating arrangements in boilers F22B37/26", - "match_score": 0.416 - }, - "F23D": { - "topic_id": "https://openalex.org/T11069", - "topic_display_name": "Testicular diseases and treatments", - "ipc_label": "BURNERS", - "match_score": 0.571 - }, - "F23G": { - "topic_id": "https://openalex.org/T14505", - "topic_display_name": "Natural Products and Applications", - "ipc_label": "CREMATION FURNACESCONSUMING WASTE PRODUCTS BY COMBUSTION", - "match_score": 0.472 - }, - "F23K": { - "topic_id": "https://openalex.org/T10806", - "topic_display_name": "Energetic Materials and Combustion", - "ipc_label": "FEEDING FUEL TO COMBUSTION APPARATUS fuel feeders specially adapted for fluidised bed combustion apparatus F23C10/22", - "match_score": 0.373 - }, - "F24S": { - "topic_id": "https://openalex.org/T10108", - "topic_display_name": "Electoral Systems and Political Participation", - "ipc_label": "SOLAR HEAT COLLECTORSSOLAR HEAT SYSTEMS for producing mechanical power from solar energy F03G6/00", - "match_score": 0.423 - }, - "F24T": { - "topic_id": "https://openalex.org/T11225", - "topic_display_name": "Geothermal Energy Systems and Applications", - "ipc_label": "GEOTHERMAL COLLECTORSGEOTHERMAL SYSTEMS", - "match_score": 0.667 - }, - "F24V": { - "topic_id": "https://openalex.org/T10171", - "topic_display_name": "Biofuel production and bioconversion", - "ipc_label": "COLLECTION, PRODUCTION OR USE OF HEAT NOT OTHERWISE PROVIDED FOR", - "match_score": 0.42 - }, - "F25B": { - "topic_id": "https://openalex.org/T13985", - "topic_display_name": "Enterprise Management and Information Systems", - "ipc_label": "REFRIGERATION MACHINES, PLANTS OR SYSTEMSCOMBINED HEATING AND REFRIGERATION SYSTEMSHEAT PUMP SYSTEMS", - "match_score": 0.414 - }, - "F25C": { - "topic_id": "https://openalex.org/T12544", - "topic_display_name": "Working Capital and Financial Performance", - "ipc_label": "PRODUCING, WORKING OR HANDLING ICE", - "match_score": 0.453 - }, - "F27M": { - "topic_id": "https://openalex.org/T10055", - "topic_display_name": "Diverse Aspects of Tourism Research", - "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS OF THE CHARGES OR FURNACES, KILNS, OVENS OR RETORTS", - "match_score": 0.41 - }, - "F28F": { - "topic_id": "https://openalex.org/T11655", - "topic_display_name": "HIV-related health complications and treatments", - "ipc_label": "DETAILS OF HEAT-EXCHANGE AND HEAT-TRANSFER APPARATUS, OF GENERAL APPLICATION water and air traps, air venting F16", - "match_score": 0.412 - }, - "F41A": { - "topic_id": "https://openalex.org/T13468", - "topic_display_name": "Educational Research and Science Teaching", - "ipc_label": "FUNCTIONAL FEATURES OR DETAILS COMMON TO BOTH SMALLARMS AND ORDNANCE, e.g. CANNONSMOUNTINGS FOR SMALLARMS OR ORDNANCE", - "match_score": 0.367 - }, - "F41G": { - "topic_id": "https://openalex.org/T13049", - "topic_display_name": "Surface Roughness and Optical Measurements", - "ipc_label": "WEAPON SIGHTSAIMING optical aspects thereof G02B", - "match_score": 0.467 - }, - "F99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "G01F": { - "topic_id": "https://openalex.org/T10836", - "topic_display_name": "Metabolomics and Mass Spectrometry Studies", - "ipc_label": "MEASURING VOLUME, VOLUME FLOW, MASS FLOW OR LIQUID LEVELMETERING BY VOLUME", - "match_score": 0.379 - }, - "G01G": { - "topic_id": "https://openalex.org/T13960", - "topic_display_name": "Dietetics, Nutrition, and Education", - "ipc_label": "WEIGHING sorting by weighing B07C5/16", - "match_score": 0.364 - }, - "G01H": { - "topic_id": "https://openalex.org/T10386", - "topic_display_name": "Microstructure and Mechanical Properties of Steels", - "ipc_label": "MEASUREMENT OF MECHANICAL VIBRATIONS OR ULTRASONIC, SONIC OR INFRASONIC WAVES", - "match_score": 0.425 - }, - "G01L": { - "topic_id": "https://openalex.org/T10386", - "topic_display_name": "Microstructure and Mechanical Properties of Steels", - "ipc_label": "MEASURING FORCE, STRESS, TORQUE, WORK, MECHANICAL POWER, MECHANICAL EFFICIENCY, OR FLUID PRESSURE weighing G01G", - "match_score": 0.385 - }, - "G01Q": { - "topic_id": "https://openalex.org/T10801", - "topic_display_name": "Synthetic Aperture Radar (SAR) Applications and Techniques", - "ipc_label": "SCANNING-PROBE TECHNIQUES OR APPARATUSAPPLICATIONS OF SCANNING-PROBE TECHNIQUES, e.g. SCANNING PROBE MICROSCOPY [SPM]", - "match_score": 0.389 - }, - "G01R": { - "topic_id": "https://openalex.org/T10614", - "topic_display_name": "Transcranial Magnetic Stimulation Studies", - "ipc_label": "MEASURING ELECTRIC VARIABLESMEASURING MAGNETIC VARIABLES indicating correct tuning of resonant circuits H03J3/12", - "match_score": 0.379 - }, - "G02B": { - "topic_id": "https://openalex.org/T12391", - "topic_display_name": "Artificial Immune Systems Applications", - "ipc_label": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS", - "match_score": 0.579 - }, - "G04D": { - "topic_id": "https://openalex.org/T13583", - "topic_display_name": "Jury Decision Making Processes", - "ipc_label": "APPARATUS OR TOOLS SPECIALLY DESIGNED FOR MAKING OR MAINTAINING CLOCKS OR WATCHES", - "match_score": 0.378 - }, - "G04F": { - "topic_id": "https://openalex.org/T13293", - "topic_display_name": "Engineering and Test Systems", - "ipc_label": "TIME-INTERVAL MEASURING measuring pulse characteristics G01R, e.g. G01R29/02; in radar or like systems G01S", - "match_score": 0.37 - }, - "G04G": { - "topic_id": "https://openalex.org/T10350", - "topic_display_name": "Electronic Health Records Systems", - "ipc_label": "ELECTRONIC TIME-PIECES", - "match_score": 0.582 - }, - "G04R": { - "topic_id": "https://openalex.org/T12810", - "topic_display_name": "Real-time simulation and control systems", - "ipc_label": "RADIO-CONTROLLED TIME-PIECES", - "match_score": 0.441 - }, - "G05D": { - "topic_id": "https://openalex.org/T10504", - "topic_display_name": "Sensorless Control of Electric Motors", - "ipc_label": "SYSTEMS FOR CONTROLLING OR REGULATING NON-ELECTRIC VARIABLES", - "match_score": 0.536 - }, - "G06C": { - "topic_id": "https://openalex.org/T13155", - "topic_display_name": "Digital Communication and Language", - "ipc_label": "DIGITAL COMPUTERS IN WHICH ALL THE COMPUTATION IS EFFECTED MECHANICALLY score computers for card games A63F1/18", - "match_score": 0.372 - }, - "G06D": { - "topic_id": "https://openalex.org/T12923", - "topic_display_name": "Digital Image Processing Techniques", - "ipc_label": "DIGITAL FLUID-PRESSURE COMPUTING DEVICES", - "match_score": 0.587 - }, - "G06F": { - "topic_id": "https://openalex.org/T13093", - "topic_display_name": "Electric Power Systems and Control", - "ipc_label": "ELECTRIC DIGITAL DATA PROCESSING computer systems based on specific computational models G06N", - "match_score": 0.472 - }, - "G06G": { - "topic_id": "https://openalex.org/T11429", - "topic_display_name": "Semiconductor Lasers and Optical Devices", - "ipc_label": "ANALOGUE COMPUTERS analogue optical computing devices G06E3/00", - "match_score": 0.529 - }, - "G06K": { - "topic_id": "https://openalex.org/T10627", - "topic_display_name": "Advanced Image and Video Retrieval Techniques", - "ipc_label": "GRAPHICAL DATA READING image or video recognition or understanding G06VPRESENTATION OF DATARECORD CARRIERSHANDLING RECORD CARRIERS", - "match_score": 0.354 - }, - "G06N": { - "topic_id": "https://openalex.org/T13806", - "topic_display_name": "Mathematical and Computational Methods", - "ipc_label": "COMPUTING ARRANGEMENTS BASED ON SPECIFIC COMPUTATIONAL MODELS", - "match_score": 0.525 - }, - "G06T": { - "topic_id": "https://openalex.org/T14339", - "topic_display_name": "Image Processing and 3D Reconstruction", - "ipc_label": "IMAGE DATA PROCESSING OR GENERATION, IN GENERAL", - "match_score": 0.541 - }, - "G06V": { - "topic_id": "https://openalex.org/T13579", - "topic_display_name": "Image and Video Stabilization", - "ipc_label": "IMAGE OR VIDEO RECOGNITION OR UNDERSTANDING", - "match_score": 0.75 - }, - "G07G": { - "topic_id": "https://openalex.org/T13321", - "topic_display_name": "Radio, Podcasts, and Digital Media", - "ipc_label": "REGISTERING THE RECEIPT OF CASH, VALUABLES, OR TOKENS digital computing in general G06C, G06F", - "match_score": 0.378 - }, - "G08B": { - "topic_id": "https://openalex.org/T11902", - "topic_display_name": "Intelligent Tutoring Systems and Adaptive Learning", - "ipc_label": "SIGNALLING OR CALLING SYSTEMSORDER TELEGRAPHSALARM SYSTEMS", - "match_score": 0.5 - }, - "G09F": { - "topic_id": "https://openalex.org/T14032", - "topic_display_name": "History and International Relations", - "ipc_label": "DISPLAYINGADVERTISINGSIGNSLABELS OR NAME-PLATESSEALS", - "match_score": 0.391 - }, - "G10L": { - "topic_id": "https://openalex.org/T13244", - "topic_display_name": "Analysis of environmental and stochastic processes", - "ipc_label": "SPEECH ANALYSIS OR SYNTHESISSPEECH RECOGNITIONSPEECH OR VOICE PROCESSINGSPEECH OR AUDIO CODING OR DECODING", - "match_score": 0.359 - }, - "G11C": { - "topic_id": "https://openalex.org/T10472", - "topic_display_name": "Semiconductor materials and devices", - "ipc_label": "STATIC STORES semiconductor memory devices H10B", - "match_score": 0.61 - }, - "G16C": { - "topic_id": "https://openalex.org/T10192", - "topic_display_name": "Catalytic Processes in Materials Science", - "ipc_label": "COMPUTATIONAL CHEMISTRYCHEMOINFORMATICSCOMPUTATIONAL MATERIALS SCIENCE", - "match_score": 0.527 - }, - "G16H": { - "topic_id": "https://openalex.org/T11773", - "topic_display_name": "Healthcare Operations and Scheduling Optimization", - "ipc_label": "HEALTHCARE INFORMATICS, i.e. INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR THE HANDLING OR PROCESSING OF MEDICAL OR HEALTHCARE DATA", - "match_score": 0.384 - }, - "G16Y": { - "topic_id": "https://openalex.org/T13952", - "topic_display_name": "Information Technology and Learning", - "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]", - "match_score": 0.508 - }, - "G16Z": { - "topic_id": "https://openalex.org/T12734", - "topic_display_name": "Information Systems and Technology Applications", - "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.456 - }, - "G21B": { - "topic_id": "https://openalex.org/T10592", - "topic_display_name": "Fusion materials and technologies", - "ipc_label": "FUSION REACTORS uncontrolled reactors G21J", - "match_score": 0.48 - }, - "G21C": { - "topic_id": "https://openalex.org/T10808", - "topic_display_name": "Electric and Hybrid Vehicle Technologies", - "ipc_label": "NUCLEAR REACTORS fusion reactors, hybrid fission-fusion reactors G21B; nuclear explosives G21J", - "match_score": 0.388 - }, - "G21D": { - "topic_id": "https://openalex.org/T12295", - "topic_display_name": "Foucault, Power, and Ethics", - "ipc_label": "NUCLEAR POWER PLANT", - "match_score": 0.565 - }, - "G21J": { - "topic_id": "https://openalex.org/T12405", - "topic_display_name": "Characterization and Applications of Magnetic Nanoparticles", - "ipc_label": "NUCLEAR EXPLOSIVESAPPLICATIONS THEREOF electric or magnetic analogue computers, e.g. simulators, for nuclear physics G06G7/54", - "match_score": 0.413 - }, - "G99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "H01C": { - "topic_id": "https://openalex.org/T12454", - "topic_display_name": "European Political History Analysis", - "ipc_label": "RESISTORS", - "match_score": 0.625 - }, - "H01J": { - "topic_id": "https://openalex.org/T12495", - "topic_display_name": "Electrostatic Discharge in Electronics", - "ipc_label": "ELECTRIC DISCHARGE TUBES OR DISCHARGE LAMPS spark-gaps H01T; arc lamps with consumable electrodes H05B; particle accelerators H05H", - "match_score": 0.381 - }, - "H01M": { - "topic_id": "https://openalex.org/T12495", - "topic_display_name": "Electrostatic Discharge in Electronics", - "ipc_label": "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE DIRECT CONVERSION OF CHEMICAL ENERGY INTO ELECTRICAL ENERGY", - "match_score": 0.383 - }, - "H01P": { - "topic_id": "https://openalex.org/T11429", - "topic_display_name": "Semiconductor Lasers and Optical Devices", - "ipc_label": "WAVEGUIDESRESONATORS, LINES, OR OTHER DEVICES OF THE WAVEGUIDE TYPE operating at optical frequencies G02B", - "match_score": 0.4 - }, - "H01Q": { - "topic_id": "https://openalex.org/T10579", - "topic_display_name": "Cognitive Radio Networks and Spectrum Sensing", - "ipc_label": "ANTENNAS, i.e. RADIO AERIALS radiators or antennas for microwave heating H05B6/72", - "match_score": 0.397 - }, - "H02B": { - "topic_id": "https://openalex.org/T10968", - "topic_display_name": "Statistical Distribution Estimation and Applications", - "ipc_label": "BOARDS, SUBSTATIONS OR SWITCHING ARRANGEMENTS FOR THE SUPPLY OR DISTRIBUTION OF ELECTRIC POWER", - "match_score": 0.411 - }, - "H02G": { - "topic_id": "https://openalex.org/T10607", - "topic_display_name": "Magnetic and transport properties of perovskites and related materials", - "ipc_label": "INSTALLATION OF ELECTRIC CABLES OR LINES, OR OF COMBINED OPTICAL AND ELECTRIC CABLES OR LINES", - "match_score": 0.444 - }, - "H02J": { - "topic_id": "https://openalex.org/T12111", - "topic_display_name": "Industrial Vision Systems and Defect Detection", - "ipc_label": "CIRCUIT ARRANGEMENTS OR SYSTEMS FOR SUPPLYING OR DISTRIBUTING ELECTRIC POWERSYSTEMS FOR STORING ELECTRIC ENERGY", - "match_score": 0.369 - }, - "H02N": { - "topic_id": "https://openalex.org/T10768", - "topic_display_name": "Electric Vehicles and Infrastructure", - "ipc_label": "ELECTRIC MACHINES NOT OTHERWISE PROVIDED FOR", - "match_score": 0.475 - }, - "H03C": { - "topic_id": "https://openalex.org/T10030", - "topic_display_name": "Electrocatalysts for Energy Conversion", - "ipc_label": "MODULATION masers or lasers H01S; coding, decoding or code conversion H03M", - "match_score": 0.429 - }, - "H03G": { - "topic_id": "https://openalex.org/T13924", - "topic_display_name": "Internet of Things and Social Network Interactions", - "ipc_label": "CONTROL OF AMPLIFICATION impedance networks, e.g. attenuators, H03H; control of transmission in lines H04B3/04", - "match_score": 0.375 - }, - "H03J": { - "topic_id": "https://openalex.org/T14117", - "topic_display_name": "Integrated Circuits and Semiconductor Failure Analysis", - "ipc_label": "TUNING RESONANT CIRCUITSSELECTING RESONANT CIRCUITS", - "match_score": 0.476 - }, - "H03L": { - "topic_id": "https://openalex.org/T13257", - "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", - "ipc_label": "AUTOMATIC CONTROL, STARTING, SYNCHRONISATION, OR STABILISATION OF GENERATORS OF ELECTRONIC OSCILLATIONS OR PULSES of dynamo-electric generators H02P", - "match_score": 0.355 - }, - "H04B": { - "topic_id": "https://openalex.org/T12804", - "topic_display_name": "Thermal Analysis in Power Transmission", - "ipc_label": "TRANSMISSION", - "match_score": 1.0 - }, - "H04H": { - "topic_id": "https://openalex.org/T12593", - "topic_display_name": "Communication in Education and Healthcare", - "ipc_label": "BROADCAST COMMUNICATION multiplex communication H04J; pictorial communication aspects of broadcast systems H04N", - "match_score": 0.408 - }, - "H04K": { - "topic_id": "https://openalex.org/T13317", - "topic_display_name": "Media, Communication, and Education", - "ipc_label": "SECRET COMMUNICATIONJAMMING OF COMMUNICATION", - "match_score": 0.633 - }, - "H04L": { - "topic_id": "https://openalex.org/T12607", - "topic_display_name": "Personal Information Management and User Behavior", - "ipc_label": "TRANSMISSION OF DIGITAL INFORMATION, e.g. TELEGRAPHIC COMMUNICATION arrangements common to telegraphic and telephonic communication H04M", - "match_score": 0.422 - }, - "H04M": { - "topic_id": "https://openalex.org/T13905", - "topic_display_name": "Telecommunications and Broadcasting Technologies", - "ipc_label": "TELEPHONIC COMMUNICATION circuits for controlling other apparatus via a telephone cable and not involving telephone switching apparatus G08", - "match_score": 0.374 - }, - "H04N": { - "topic_id": "https://openalex.org/T13317", - "topic_display_name": "Media, Communication, and Education", - "ipc_label": "PICTORIAL COMMUNICATION, e.g. TELEVISION", - "match_score": 0.613 - }, - "H04Q": { - "topic_id": "https://openalex.org/T10575", - "topic_display_name": "Wireless Communication Networks Research", - "ipc_label": "SELECTING switches, relays, selectors H01H; wireless communication networks H04W", - "match_score": 0.55 - }, - "H04S": { - "topic_id": "https://openalex.org/T11575", - "topic_display_name": "Nonlinear Photonic Systems", - "ipc_label": "STEREOPHONIC SYSTEMS", - "match_score": 0.696 - }, - "H04T": { - "topic_id": "https://openalex.org/T11121", - "topic_display_name": "Public Relations and Crisis Communication", - "ipc_label": "INDEXING SCHEME RELATING TO STANDARDS FOR ELECTRIC COMMUNICATION TECHNIQUE CLASS H04", - "match_score": 0.512 - }, - "H04W": { - "topic_id": "https://openalex.org/T10575", - "topic_display_name": "Wireless Communication Networks Research", - "ipc_label": "WIRELESS COMMUNICATION NETWORKS broadcast communication H04H; communication systems using wireless links for non-selective communication, e.g. wireless extensions H04M1/72", - "match_score": 0.36 - }, - "H05B": { - "topic_id": "https://openalex.org/T13093", - "topic_display_name": "Electric Power Systems and Control", - "ipc_label": "ELECTRIC HEATINGELECTRIC LIGHT SOURCES NOT OTHERWISE PROVIDED FORCIRCUIT ARRANGEMENTS FOR ELECTRIC LIGHT SOURCES, IN GENERAL", - "match_score": 0.36 - }, - "H10B": { - "topic_id": "https://openalex.org/T10299", - "topic_display_name": "Photonic and Optical Devices", - "ipc_label": "ELECTRONIC MEMORY DEVICES", - "match_score": 0.667 - }, - "H10K": { - "topic_id": "https://openalex.org/T10045", - "topic_display_name": "Organic Electronics and Photovoltaics", - "ipc_label": "ORGANIC ELECTRIC SOLID-STATE DEVICES", - "match_score": 0.658 - }, - "H10N": { - "topic_id": "https://openalex.org/T10768", - "topic_display_name": "Electric Vehicles and Infrastructure", - "ipc_label": "ELECTRIC SOLID-STATE DEVICES NOT OTHERWISE PROVIDED FOR", - "match_score": 0.44 - }, - "H99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "Y02A": { - "topic_id": "https://openalex.org/T10895", - "topic_display_name": "Species Distribution and Climate Change", - "ipc_label": "TECHNOLOGIES FOR ADAPTATION TO CLIMATE CHANGE", - "match_score": 0.643 - }, - "Y02B": { - "topic_id": "https://openalex.org/T13734", - "topic_display_name": "Advanced Computational Techniques and Applications", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO BUILDINGS, e.g. HOUSING, HOUSE APPLIANCES OR RELATED END-USER APPLICATIONS", - "match_score": 0.425 - }, - "Y02C": { - "topic_id": "https://openalex.org/T10945", - "topic_display_name": "Lysosomal Storage Disorders Research", - "ipc_label": "CAPTURE, STORAGE, SEQUESTRATION OR DISPOSAL OF GREENHOUSE GASES [GHG]", - "match_score": 0.419 - }, - "Y02P": { - "topic_id": "https://openalex.org/T11488", - "topic_display_name": "Climate Change Communication and Perception", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES IN THE PRODUCTION OR PROCESSING OF GOODS", - "match_score": 0.525 - }, - "Y02T": { - "topic_id": "https://openalex.org/T11488", - "topic_display_name": "Climate Change Communication and Perception", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO TRANSPORTATION", - "match_score": 0.598 - }, - "Y02W": { - "topic_id": "https://openalex.org/T11404", - "topic_display_name": "Irrigation Practices and Water Management", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO WASTEWATER TREATMENT OR WASTE MANAGEMENT", - "match_score": 0.504 - }, - "Y10S": { - "topic_id": "https://openalex.org/T13332", - "topic_display_name": "Historical Studies on Reproduction, Gender, Health, and Societal Changes", - "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER USPC CROSS-REFERENCE ART COLLECTIONS [XRACs] AND DIGESTS", - "match_score": 0.412 - }, - "Y10T": { - "topic_id": "https://openalex.org/T10885", - "topic_display_name": "Gene expression and cancer classification", - "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER US CLASSIFICATION", - "match_score": 0.484 - } - }, - "subclass": { - "A01D": { - "topic_id": "https://openalex.org/T13896", - "topic_display_name": "Health Services Management and Policy", - "ipc_label": "HARVESTINGMOWING", - "match_score": 0.412 - }, - "A01H": { - "topic_id": "https://openalex.org/T10442", - "topic_display_name": "Knee injuries and reconstruction techniques", - "ipc_label": "NEW PLANTS OR NON-TRANSGENIC PROCESSES FOR OBTAINING THEMPLANT REPRODUCTION BY TISSUE CULTURE TECHNIQUES", - "match_score": 0.435 - }, - "A01J": { - "topic_id": "https://openalex.org/T11386", - "topic_display_name": "Bee Products Chemical Analysis", - "ipc_label": "MANUFACTURE OF DAIRY PRODUCTS for chemical matters, see subclass A23C", - "match_score": 0.465 - }, - "A01L": { - "topic_id": "https://openalex.org/T11905", - "topic_display_name": "Veterinary Pharmacology and Anesthesia", - "ipc_label": "SHOEING OF ANIMALS", - "match_score": 0.581 - }, - "A01P": { - "topic_id": "https://openalex.org/T14099", - "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", - "ipc_label": "BIOCIDAL, PEST REPELLANT, PEST ATTRACTANT OR PLANT GROWTH REGULATORY ACTIVITY OF CHEMICAL COMPOUNDS OR PREPARATIONS", - "match_score": 0.386 - }, - "A21C": { - "topic_id": "https://openalex.org/T12282", - "topic_display_name": "Mineral Processing and Grinding", - "ipc_label": "MACHINES OR EQUIPMENT FOR MAKING OR PROCESSING DOUGHSHANDLING BAKED ARTICLES MADE FROM DOUGH", - "match_score": 0.39 - }, - "A22B": { - "topic_id": "https://openalex.org/T13366", - "topic_display_name": "Accounting Theory and Financial Reporting", - "ipc_label": "SLAUGHTERING", - "match_score": 0.545 - }, - "A23K": { - "topic_id": "https://openalex.org/T12181", - "topic_display_name": "Agricultural and Biological Research", - "ipc_label": "FODDER", - "match_score": 0.444 - }, - "A23Y": { - "topic_id": "https://openalex.org/T12388", - "topic_display_name": "Identification and Quantification in Food", - "ipc_label": "INDEXING SCHEME RELATING TO LACTIC OR PROPIONIC ACID BACTERIA USED IN FOODSTUFFS OR FOOD PREPARATION", - "match_score": 0.369 - }, - "A24C": { - "topic_id": "https://openalex.org/T13832", - "topic_display_name": "Advanced Decision-Making Techniques", - "ipc_label": "MACHINES FOR MAKING CIGARS OR CIGARETTES", - "match_score": 0.475 - }, - "A41B": { - "topic_id": "https://openalex.org/T13368", - "topic_display_name": "University Challenges and Reforms", - "ipc_label": "SHIRTSUNDERWEARBABY LINENHANDKERCHIEFS", - "match_score": 0.451 - }, - "A41C": { - "topic_id": "https://openalex.org/T14190", - "topic_display_name": "Military history and social perspectives", - "ipc_label": "CORSETSBRASSIERES", - "match_score": 0.485 - }, - "A41D": { - "topic_id": "https://openalex.org/T13272", - "topic_display_name": "Psychological Treatments and Assessments", - "ipc_label": "OUTERWEARPROTECTIVE GARMENTSACCESSORIES", - "match_score": 0.43 - }, - "A41F": { - "topic_id": "https://openalex.org/T13129", - "topic_display_name": "Material Properties and Applications", - "ipc_label": "GARMENT FASTENINGSSUSPENDERS", - "match_score": 0.491 - }, - "A41G": { - "topic_id": "https://openalex.org/T13734", - "topic_display_name": "Advanced Computational Techniques and Applications", - "ipc_label": "ARTIFICIAL FLOWERSWIGSMASKSFEATHERS", - "match_score": 0.552 - }, - "A42C": { - "topic_id": "https://openalex.org/T11159", - "topic_display_name": "Manufacturing Process and Optimization", - "ipc_label": "MANUFACTURING OR TRIMMING HEAD COVERINGS, e.g. HATS", - "match_score": 0.494 - }, - "A43B": { - "topic_id": "https://openalex.org/T13232", - "topic_display_name": "Laser-Ablation Synthesis of Nanoparticles", - "ipc_label": "CHARACTERISTIC FEATURES OF FOOTWEARPARTS OF FOOTWEAR", - "match_score": 0.387 - }, - "A43C": { - "topic_id": "https://openalex.org/T13288", - "topic_display_name": "Banking, Crisis Management, COVID-19 Impact", - "ipc_label": "FASTENINGS OR ATTACHMENTS OF FOOTWEARLACES IN GENERAL", - "match_score": 0.375 - }, - "A43D": { - "topic_id": "https://openalex.org/T13290", - "topic_display_name": "Diverse Industrial Engineering Technologies", - "ipc_label": "MACHINES, TOOLS, EQUIPMENT OR METHODS FOR MANUFACTURING OR REPAIRING FOOTWEAR", - "match_score": 0.462 - }, - "A44C": { - "topic_id": "https://openalex.org/T12607", - "topic_display_name": "Personal Information Management and User Behavior", - "ipc_label": "PERSONAL ADORNMENTS, e.g. JEWELLERYCOINS", - "match_score": 0.449 - }, - "A44D": { - "topic_id": "https://openalex.org/T11334", - "topic_display_name": "Psychosomatic Disorders and Their Treatments", - "ipc_label": "INDEXING SCHEME RELATING TO BUTTONS, PINS, BUCKLES OR SLIDE FASTENERS, AND TO JEWELLERY, BRACELETS OR OTHER PERSONAL ADORNMENTS", - "match_score": 0.374 - }, - "A45C": { - "topic_id": "https://openalex.org/T10413", - "topic_display_name": "High-pressure geophysics and materials", - "ipc_label": "PURSESLUGGAGEHAND CARRIED BAGS", - "match_score": 0.471 - }, - "A45F": { - "topic_id": "https://openalex.org/T11867", - "topic_display_name": "Traumatic Ocular and Foreign Body Injuries", - "ipc_label": "TRAVELLING OR CAMP EQUIPMENT: SACKS OR PACKS CARRIED ON THE BODY", - "match_score": 0.358 - }, - "A46B": { - "topic_id": "https://openalex.org/T13398", - "topic_display_name": "Data Analysis with R", - "ipc_label": "BRUSHES handles not integral with brushware B25G", - "match_score": 0.353 - }, - "A46D": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "MANUFACTURE OF BRUSHES", - "match_score": 0.455 - }, - "A47B": { - "topic_id": "https://openalex.org/T14133", - "topic_display_name": "Border Security and International Relations", - "ipc_label": "TABLESDESKSOFFICE FURNITURECABINETSDRAWERSGENERAL DETAILS OF FURNITURE furniture jointing F16B", - "match_score": 0.35 - }, - "A47C": { - "topic_id": "https://openalex.org/T10495", - "topic_display_name": "Catalysts for Methane Reforming", - "ipc_label": "CHAIRS seats specially adapted for vehicles B60N2/00SOFASBEDS upholstery in general B68G", - "match_score": 0.353 - }, - "A47G": { - "topic_id": "https://openalex.org/T14160", - "topic_display_name": "Water management and technologies", - "ipc_label": "HOUSEHOLD OR TABLE EQUIPMENT book-ends A47B5/00; knives B26B", - "match_score": 0.366 - }, - "A47J": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "KITCHEN EQUIPMENTCOFFEE MILLSSPICE MILLSAPPARATUS FOR MAKING BEVERAGES", - "match_score": 0.378 - }, - "A61D": { - "topic_id": "https://openalex.org/T14236", - "topic_display_name": "Educational Tools and Methods", - "ipc_label": "VETERINARY INSTRUMENTS, IMPLEMENTS, TOOLS, OR METHODS", - "match_score": 0.512 - }, - "A61P": { - "topic_id": "https://openalex.org/T12685", - "topic_display_name": "Phytochemical compounds biological activities", - "ipc_label": "SPECIFIC THERAPEUTIC ACTIVITY OF CHEMICAL COMPOUNDS OR MEDICINAL PREPARATIONS", - "match_score": 0.525 - }, - "A61Q": { - "topic_id": "https://openalex.org/T10576", - "topic_display_name": "Opioid Use Disorder Treatment", - "ipc_label": "SPECIFIC USE OF COSMETICS OR SIMILAR TOILETRY PREPARATIONS", - "match_score": 0.437 - }, - "A62D": { - "topic_id": "https://openalex.org/T11802", - "topic_display_name": "Chemical Looping and Thermochemical Processes", - "ipc_label": "CHEMICAL MEANS FOR EXTINGUISHING FIRES OR FOR COMBATING OR PROTECTING AGAINST HARMFUL CHEMICAL AGENTSCHEMICAL MATERIALS FOR USE IN BREATHING APPARATUS", - "match_score": 0.369 - }, - "A63H": { - "topic_id": "https://openalex.org/T12105", - "topic_display_name": "Hygrothermal properties of building materials", - "ipc_label": "TOYS, e.g. TOPS, DOLLS, HOOPS OR BUILDING BLOCKS", - "match_score": 0.409 - }, - "A99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "B01B": { - "topic_id": "https://openalex.org/T11900", - "topic_display_name": "Fungal Plant Pathogen Control", - "ipc_label": "BOILINGBOILING APPARATUS ; EVAPORATION; EVAPORATION APPARATUS", - "match_score": 0.381 - }, - "B01J": { - "topic_id": "https://openalex.org/T13104", - "topic_display_name": "Chemical and Physical Properties of Materials", - "ipc_label": "CHEMICAL OR PHYSICAL PROCESSES, e.g. CATALYSIS OR COLLOID CHEMISTRYTHEIR RELEVANT APPARATUS", - "match_score": 0.471 - }, - "B01L": { - "topic_id": "https://openalex.org/T13104", - "topic_display_name": "Chemical and Physical Properties of Materials", - "ipc_label": "CHEMICAL OR PHYSICAL LABORATORY APPARATUS FOR GENERAL USE", - "match_score": 0.549 - }, - "B03B": { - "topic_id": "https://openalex.org/T11808", - "topic_display_name": "Superconducting Materials and Applications", - "ipc_label": "SEPARATING SOLID MATERIALS USING LIQUIDS OR USING PNEUMATIC TABLES OR JIGS", - "match_score": 0.448 - }, - "B09B": { - "topic_id": "https://openalex.org/T11108", - "topic_display_name": "Municipal Solid Waste Management", - "ipc_label": "DISPOSAL OF SOLID WASTE", - "match_score": 0.667 - }, - "B21G": { - "topic_id": "https://openalex.org/T10377", - "topic_display_name": "Metal and Thin Film Mechanics", - "ipc_label": "MAKING NEEDLES, PINS OR NAILS OF METAL", - "match_score": 0.4 - }, - "B22C": { - "topic_id": "https://openalex.org/T11853", - "topic_display_name": "Semiconductor materials and interfaces", - "ipc_label": "FOUNDRY MOULDING moulding refractory materials in general B28B", - "match_score": 0.48 - }, - "B23B": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "TURNINGBORING arrangements for copying or controlling B23Q", - "match_score": 0.424 - }, - "B24C": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "ABRASIVE OR RELATED BLASTING WITH PARTICULATE MATERIAL", - "match_score": 0.469 - }, - "B25H": { - "topic_id": "https://openalex.org/T10488", - "topic_display_name": "Nanocomposite Films for Food Packaging", - "ipc_label": "WORKSHOP EQUIPMENT, e.g. FOR MARKING-OUT WORKSTORAGE MEANS FOR WORKSHOPS storing or packaging B65", - "match_score": 0.356 - }, - "B27H": { - "topic_id": "https://openalex.org/T14076", - "topic_display_name": "Material Properties and Failure Mechanisms", - "ipc_label": "BENDING WOOD OR SIMILAR MATERIALCOOPERAGEMAKING WHEELS FROM WOOD OR SIMILAR MATERIAL", - "match_score": 0.381 - }, - "B27J": { - "topic_id": "https://openalex.org/T10219", - "topic_display_name": "Mechanical Behavior of Composites", - "ipc_label": "MECHANICAL WORKING OF CANE, CORK, OR SIMILAR MATERIALS", - "match_score": 0.575 - }, - "B28D": { - "topic_id": "https://openalex.org/T10811", - "topic_display_name": "Hydrogen Storage and Materials", - "ipc_label": "WORKING STONE OR STONE-LIKE MATERIALS", - "match_score": 0.567 - }, - "B29L": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS B29C, RELATING TO PARTICULAR ARTICLES", - "match_score": 0.393 - }, - "B41F": { - "topic_id": "https://openalex.org/T11523", - "topic_display_name": "Nanomaterials and Printing Technologies", - "ipc_label": "PRINTING MACHINES OR PRESSES manifolding devices or office printing machines B41L", - "match_score": 0.383 - }, - "B41P": { - "topic_id": "https://openalex.org/T13557", - "topic_display_name": "Environmental and sustainability education", - "ipc_label": "INDEXING SCHEME RELATING TO PRINTING, LINING MACHINES, TYPEWRITERS, AND TO STAMPS", - "match_score": 0.42 - }, - "B42P": { - "topic_id": "https://openalex.org/T11877", - "topic_display_name": "Iron oxide chemistry and applications", - "ipc_label": "INDEXING SCHEME RELATING TO BOOKS, FILING APPLIANCES OR THE LIKE", - "match_score": 0.416 - }, - "B44F": { - "topic_id": "https://openalex.org/T12174", - "topic_display_name": "Hospital Admissions and Outcomes", - "ipc_label": "SPECIAL DESIGNS OR PICTURES", - "match_score": 0.542 - }, - "B60C": { - "topic_id": "https://openalex.org/T12641", - "topic_display_name": "Historical and socio-economic studies of Spain and related regions", - "ipc_label": "VEHICLE TYRESTYRE INFLATIONTYRE CHANGINGCONNECTING VALVES TO INFLATABLE ELASTIC BODIES IN GENERALDEVICES OR ARRANGEMENTS RELATED TO TYRES", - "match_score": 0.384 - }, - "B60D": { - "topic_id": "https://openalex.org/T10829", - "topic_display_name": "Interconnection Networks and Systems", - "ipc_label": "VEHICLE CONNECTIONS components of brake systems B60T17/04", - "match_score": 0.473 - }, - "B60F": { - "topic_id": "https://openalex.org/T14022", - "topic_display_name": "Cultural and Religious Practices in Indonesia", - "ipc_label": "VEHICLES FOR USE BOTH ON RAIL AND ON ROADAMPHIBIOUS OR LIKE VEHICLESCONVERTIBLE VEHICLES air-cushion vehicles B60V", - "match_score": 0.377 - }, - "B60G": { - "topic_id": "https://openalex.org/T10805", - "topic_display_name": "Vehicle Dynamics and Control Systems", - "ipc_label": "VEHICLE SUSPENSION ARRANGEMENTS air-cushion vehicles B60V; cycle suspensions B62K25/00", - "match_score": 0.361 - }, - "B60H": { - "topic_id": "https://openalex.org/T10558", - "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", - "ipc_label": "ARRANGEMENTS OF HEATING, COOLING, VENTILATING OR OTHER AIR-TREATING DEVICES SPECIALLY ADAPTED FOR PASSENGER OR GOODS SPACES OF VEHICLES", - "match_score": 0.366 - }, - "B60Q": { - "topic_id": "https://openalex.org/T10558", - "topic_display_name": "Advancements in Semiconductor Devices and Circuit Design", - "ipc_label": "ARRANGEMENT OF SIGNALLING OR LIGHTING DEVICES, THE MOUNTING OR SUPPORTING THEREOF OR CIRCUITS THEREFOR, FOR VEHICLES IN GENERAL", - "match_score": 0.415 - }, - "B60R": { - "topic_id": "https://openalex.org/T12707", - "topic_display_name": "Vehicle License Plate Recognition", - "ipc_label": "VEHICLES, VEHICLE FITTINGS, OR VEHICLE PARTS, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.381 - }, - "B60V": { - "topic_id": "https://openalex.org/T11002", - "topic_display_name": "Indoor Air Quality and Microbial Exposure", - "ipc_label": "AIR-CUSHION VEHICLES", - "match_score": 0.393 - }, - "B60Y": { - "topic_id": "https://openalex.org/T12898", - "topic_display_name": "Induction Heating and Inverter Technology", - "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS CROSS-CUTTING VEHICLE TECHNOLOGY", - "match_score": 0.569 - }, - "B61D": { - "topic_id": "https://openalex.org/T12271", - "topic_display_name": "Renewable energy and sustainable power systems", - "ipc_label": "BODY DETAILS OR KINDS OF RAILWAY VEHICLES vehicles in general B60; adaptation of vehicles to special systems B61B; underframes B61F", - "match_score": 0.35 - }, - "B61G": { - "topic_id": "https://openalex.org/T14049", - "topic_display_name": "Plant and Fungal Species Descriptions", - "ipc_label": "COUPLINGSDRAUGHT AND BUFFING APPLIANCES vehicle connections in general B60D", - "match_score": 0.446 - }, - "B61J": { - "topic_id": "https://openalex.org/T10757", - "topic_display_name": "Geographic Information Systems Studies", - "ipc_label": "SHIFTING OR SHUNTING OF RAIL VEHICLES shifting vehicles in general B60S; marshalling systems B61B", - "match_score": 0.37 - }, - "B62C": { - "topic_id": "https://openalex.org/T13551", - "topic_display_name": "Biochemical effects in animals", - "ipc_label": "VEHICLES DRAWN BY ANIMALS", - "match_score": 0.582 - }, - "B63J": { - "topic_id": "https://openalex.org/T11427", - "topic_display_name": "Elbow and Forearm Trauma Treatment", - "ipc_label": "AUXILIARIES ON VESSELS", - "match_score": 0.444 - }, - "B64B": { - "topic_id": "https://openalex.org/T12916", - "topic_display_name": "COVID-19 impact on air quality", - "ipc_label": "LIGHTER-THAN AIR AIRCRAFT", - "match_score": 0.4 - }, - "B64C": { - "topic_id": "https://openalex.org/T10647", - "topic_display_name": "Coastal and Marine Dynamics", - "ipc_label": "AEROPLANESHELICOPTERS", - "match_score": 0.49 - }, - "B64U": { - "topic_id": "https://openalex.org/T11192", - "topic_display_name": "Underwater Vehicles and Communication Systems", - "ipc_label": "UNMANNED AERIAL VEHICLES [UAV]EQUIPMENT THEREFOR", - "match_score": 0.43 - }, - "B65H": { - "topic_id": "https://openalex.org/T13917", - "topic_display_name": "Engineering and Material Science Research", - "ipc_label": "HANDLING THIN OR FILAMENTARY MATERIAL, e.g. SHEETS, WEBS, CABLES", - "match_score": 0.419 - }, - "B68B": { - "topic_id": "https://openalex.org/T12617", - "topic_display_name": "Energy, Environment, and Transportation Policies", - "ipc_label": "HARNESSDEVICES USED IN CONNECTION THEREWITHWHIPS OR THE LIKE", - "match_score": 0.389 - }, - "B68C": { - "topic_id": "https://openalex.org/T13896", - "topic_display_name": "Health Services Management and Policy", - "ipc_label": "SADDLESSTIRRUPS", - "match_score": 0.424 - }, - "B81B": { - "topic_id": "https://openalex.org/T12111", - "topic_display_name": "Industrial Vision Systems and Defect Detection", - "ipc_label": "MICROSTRUCTURAL DEVICES OR SYSTEMS, e.g. MICROMECHANICAL DEVICES piezo-electric, electrostrictive or magnetostrictive elements per se H10N30/00", - "match_score": 0.37 - }, - "B82Y": { - "topic_id": "https://openalex.org/T11169", - "topic_display_name": "Silicon Nanostructures and Photoluminescence", - "ipc_label": "SPECIFIC USES OR APPLICATIONS OF NANOSTRUCTURESMEASUREMENT OR ANALYSIS OF NANOSTRUCTURESMANUFACTURE OR TREATMENT OF NANOSTRUCTURES", - "match_score": 0.402 - }, - "B99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "C01B": { - "topic_id": "https://openalex.org/T12458", - "topic_display_name": "Organometallic Compounds Synthesis and Characterization", - "ipc_label": "NON-METALLIC ELEMENTSCOMPOUNDS THEREOF; METALLOIDS OR COMPOUNDS THEREOF NOT COVERED BY SUBCLASS C01C", - "match_score": 0.4 - }, - "C01P": { - "topic_id": "https://openalex.org/T12410", - "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", - "ipc_label": "INDEXING SCHEME RELATING TO STRUCTURAL AND PHYSICAL ASPECTS OF SOLID INORGANIC COMPOUNDS", - "match_score": 0.658 - }, - "C03B": { - "topic_id": "https://openalex.org/T10705", - "topic_display_name": "Additive Manufacturing Materials and Processes", - "ipc_label": "MANUFACTURE, SHAPING, OR SUPPLEMENTARY PROCESSES", - "match_score": 0.574 - }, - "C05B": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "PHOSPHATIC FERTILISERS", - "match_score": 0.5 - }, - "C05C": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "NITROGENOUS FERTILISERS", - "match_score": 0.444 - }, - "C05D": { - "topic_id": "https://openalex.org/T10973", - "topic_display_name": "Radioactive element chemistry and processing", - "ipc_label": "INORGANIC FERTILISERS NOT COVERED BY SUBCLASSES C05B, C05CFERTILISERS PRODUCING CARBON DIOXIDE", - "match_score": 0.362 - }, - "C06F": { - "topic_id": "https://openalex.org/T13862", - "topic_display_name": "Soil, Finite Element Methods", - "ipc_label": "MATCHESMANUFACTURE OF MATCHES", - "match_score": 0.588 - }, - "C07B": { - "topic_id": "https://openalex.org/T14099", - "topic_display_name": "Synthesis and Characterization of Heterocyclic Compounds", - "ipc_label": "GENERAL METHODS OF ORGANIC CHEMISTRYAPPARATUS THEREFOR preparation of carboxylic acid esters by telomerisation C07C67/47; telomerisation C08F", - "match_score": 0.355 - }, - "C07C": { - "topic_id": "https://openalex.org/T13208", - "topic_display_name": "Synthesis of heterocyclic compounds", - "ipc_label": "ACYCLIC OR CARBOCYCLIC COMPOUNDS", - "match_score": 0.657 - }, - "C07D": { - "topic_id": "https://openalex.org/T13208", - "topic_display_name": "Synthesis of heterocyclic compounds", - "ipc_label": "HETEROCYCLIC COMPOUNDS macromolecular compounds C08", - "match_score": 0.512 - }, - "C07G": { - "topic_id": "https://openalex.org/T12055", - "topic_display_name": "Boron Compounds in Chemistry", - "ipc_label": "COMPOUNDS OF UNKNOWN CONSTITUTION", - "match_score": 0.492 - }, - "C07J": { - "topic_id": "https://openalex.org/T10310", - "topic_display_name": "Corrosion Behavior and Inhibition", - "ipc_label": "STEROIDS seco-steroids C07C", - "match_score": 0.455 - }, - "C08C": { - "topic_id": "https://openalex.org/T13037", - "topic_display_name": "Piperaceae Chemical and Biological Studies", - "ipc_label": "TREATMENT OR CHEMICAL MODIFICATION OF RUBBERS", - "match_score": 0.506 - }, - "C08F": { - "topic_id": "https://openalex.org/T13239", - "topic_display_name": "Phosphorus compounds and reactions", - "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED BY REACTIONS ONLY INVOLVING CARBON-TO-CARBON UNSATURATED BONDS", - "match_score": 0.4 - }, - "C08G": { - "topic_id": "https://openalex.org/T14459", - "topic_display_name": "Synthesis and Reactions of Organic Compounds", - "ipc_label": "MACROMOLECULAR COMPOUNDS OBTAINED OTHERWISE THAN BY REACTIONS ONLY INVOLVING UNSATURATED CARBON-TO-CARBON BONDS", - "match_score": 0.387 - }, - "C09F": { - "topic_id": "https://openalex.org/T11823", - "topic_display_name": "Natural Resources and Economic Development", - "ipc_label": "NATURAL RESINSFRENCH POLISHDRYING-OILSDRIERS (SICCATIVES)TURPENTINE", - "match_score": 0.422 - }, - "C09G": { - "topic_id": "https://openalex.org/T12638", - "topic_display_name": "Pomegranate: compositions and health benefits", - "ipc_label": "POLISHING COMPOSITIONS French polish C09F11/00SKI WAXES", - "match_score": 0.42 - }, - "C09H": { - "topic_id": "https://openalex.org/T14032", - "topic_display_name": "History and International Relations", - "ipc_label": "PREPARATION OF GLUE OR GELATINE", - "match_score": 0.485 - }, - "C09K": { - "topic_id": "https://openalex.org/T10245", - "topic_display_name": "Metamaterials and Metasurfaces Applications", - "ipc_label": "MATERIALS FOR MISCELLANEOUS APPLICATIONS, NOT PROVIDED FOR ELSEWHERE", - "match_score": 0.523 - }, - "C10F": { - "topic_id": "https://openalex.org/T10650", - "topic_display_name": "Food Drying and Modeling", - "ipc_label": "DRYING OR WORKING-UP OF PEAT", - "match_score": 0.423 - }, - "C10H": { - "topic_id": "https://openalex.org/T12931", - "topic_display_name": "Educational Methods and Outcomes", - "ipc_label": "PRODUCTION OF ACETYLENE BY WET METHODS purification of acetylene C07C7/00", - "match_score": 0.457 - }, - "C10K": { - "topic_id": "https://openalex.org/T11848", - "topic_display_name": "Heme Oxygenase-1 and Carbon Monoxide", - "ipc_label": "PURIFYING OR MODIFYING THE CHEMICAL COMPOSITION OF COMBUSTIBLE GASES CONTAINING CARBON MONOXIDE", - "match_score": 0.412 - }, - "C10N": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASS C10M RELATING TO LUBRICATING COMPOSITIONS", - "match_score": 0.397 - }, - "C11D": { - "topic_id": "https://openalex.org/T11869", - "topic_display_name": "Per- and polyfluoroalkyl substances research", - "ipc_label": "DETERGENT COMPOSITIONSUSE OF SINGLE SUBSTANCES AS DETERGENTSSOAP OR SOAP-MAKINGRESIN SOAPSRECOVERY OF GLYCEROL", - "match_score": 0.351 - }, - "C12J": { - "topic_id": "https://openalex.org/T12008", - "topic_display_name": "Solar-Powered Water Purification Methods", - "ipc_label": "VINEGARPREPARATION OR PURIFICATION THEREOF", - "match_score": 0.61 - }, - "C12R": { - "topic_id": "https://openalex.org/T10685", - "topic_display_name": "Viral-associated cancers and disorders", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES C12C - C12Q, RELATING TO MICROORGANISMS", - "match_score": 0.367 - }, - "C12Y": { - "topic_id": "https://openalex.org/T12770", - "topic_display_name": "Amino Acid Enzymes and Metabolism", - "ipc_label": "ENZYMES", - "match_score": 1.0 - }, - "C13B": { - "topic_id": "https://openalex.org/T12410", - "topic_display_name": "Structural and Chemical Analysis of Organic and Inorganic Compounds", - "ipc_label": "PRODUCTION OF SUCROSEAPPARATUS SPECIALLY ADAPTED THEREFOR chemically synthesised sugars or sugar derivatives C07H; fermentation or enzyme-using processes for preparing compounds containing saccharide radicals C12P19/00", - "match_score": 0.351 - }, - "C21B": { - "topic_id": "https://openalex.org/T12301", - "topic_display_name": "Facial Nerve Paralysis Treatment and Research", - "ipc_label": "MANUFACTURE OF IRON OR STEEL preliminary treatment of ferrous ores or scrap C22B1/00; electric heating H05B", - "match_score": 0.368 - }, - "C22B": { - "topic_id": "https://openalex.org/T13652", - "topic_display_name": "Education and Social Development in Ukraine", - "ipc_label": "PRODUCTION AND REFINING OF METALS electrolytic C25PRETREATMENT OF RAW MATERIALS", - "match_score": 0.475 - }, - "C22C": { - "topic_id": "https://openalex.org/T11453", - "topic_display_name": "Diagnosis and Treatment of Venous Diseases", - "ipc_label": "ALLOYS flints C06C15/00; treatment of alloys C21D, C22F", - "match_score": 0.474 - }, - "C23D": { - "topic_id": "https://openalex.org/T13463", - "topic_display_name": "Nanoporous metals and alloys", - "ipc_label": "ENAMELLING OF, OR APPLYING A VITREOUS LAYER TO, METALS", - "match_score": 0.39 - }, - "C23G": { - "topic_id": "https://openalex.org/T14068", - "topic_display_name": "Organic and Inorganic Chemical Reactions", - "ipc_label": "CLEANING OR DE-GREASING OF METALLIC MATERIAL BY CHEMICAL METHODS OTHER THAN ELECTROLYSIS", - "match_score": 0.438 - }, - "C25C": { - "topic_id": "https://openalex.org/T10962", - "topic_display_name": "Thermodynamic properties of mixtures", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC PRODUCTION, RECOVERY OR REFINING OF METALSAPPARATUS THEREFOR", - "match_score": 0.378 - }, - "C25D": { - "topic_id": "https://openalex.org/T14382", - "topic_display_name": "Electrophoretic Deposition in Materials Science", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC OR ELECTROPHORETIC PRODUCTION OF COATINGSELECTROFORMINGAPPARATUS THEREFOR", - "match_score": 0.424 - }, - "C25F": { - "topic_id": "https://openalex.org/T11025", - "topic_display_name": "Nonlinear Optical Materials Research", - "ipc_label": "PROCESSES FOR THE ELECTROLYTIC REMOVAL OF MATERIALS FROM OBJECTSAPPARATUS THEREFOR", - "match_score": 0.458 - }, - "C99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "D01D": { - "topic_id": "https://openalex.org/T11416", - "topic_display_name": "Numerical methods for differential equations", - "ipc_label": "MECHANICAL METHODS OR APPARATUS IN THE MANUFACTURE OF ARTIFICIAL FILAMENTS, THREADS, FIBRES, BRISTLES OR RIBBONS", - "match_score": 0.397 - }, - "D02G": { - "topic_id": "https://openalex.org/T14192", - "topic_display_name": "Literature, Film, and Journalism Analysis", - "ipc_label": "CRIMPING OR CURLING FIBRES, FILAMENTS, THREADS, OR YARNSYARNS OR THREADS", - "match_score": 0.389 - }, - "D02H": { - "topic_id": "https://openalex.org/T13523", - "topic_display_name": "Mathematics, Computing, and Information Processing", - "ipc_label": "WARPING, BEAMING OR LEASING", - "match_score": 0.468 - }, - "D03C": { - "topic_id": "https://openalex.org/T12490", - "topic_display_name": "Software Engineering and Design Patterns", - "ipc_label": "SHEDDING MECHANISMSPATTERN CARDS OR CHAINSPUNCHING OF CARDSDESIGNING PATTERNS", - "match_score": 0.41 - }, - "D03D": { - "topic_id": "https://openalex.org/T13880", - "topic_display_name": "Innovative Education Methods and Tools", - "ipc_label": "WOVEN FABRICSMETHODS OF WEAVINGLOOMS", - "match_score": 0.459 - }, - "D03J": { - "topic_id": "https://openalex.org/T10262", - "topic_display_name": "Microwave Engineering and Waveguides", - "ipc_label": "AUXILIARY WEAVING APPARATUSWEAVERS' TOOLSSHUTTLES", - "match_score": 0.4 - }, - "D04B": { - "topic_id": "https://openalex.org/T13366", - "topic_display_name": "Accounting Theory and Financial Reporting", - "ipc_label": "KNITTING", - "match_score": 0.556 - }, - "D05C": { - "topic_id": "https://openalex.org/T13583", - "topic_display_name": "Jury Decision Making Processes", - "ipc_label": "EMBROIDERINGTUFTING making non-woven fabrics D04H; sewing D05B", - "match_score": 0.391 - }, - "D05D": { - "topic_id": "https://openalex.org/T14497", - "topic_display_name": "Social Issues and Policies in Latin America", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES D05B AND D05C, RELATING TO SEWING, EMBROIDERING AND TUFTING", - "match_score": 0.4 - }, - "D06C": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "FINISHING, DRESSING, TENTERING OR STRETCHING TEXTILE FABRICS", - "match_score": 0.484 - }, - "D06F": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "LAUNDERING, DRYING, IRONING, PRESSING OR FOLDING TEXTILE ARTICLES", - "match_score": 0.44 - }, - "D06H": { - "topic_id": "https://openalex.org/T11948", - "topic_display_name": "Machine Learning in Materials Science", - "ipc_label": "MARKING, INSPECTING, SEAMING OR SEVERING TEXTILE MATERIALS seaming by sewing D05B", - "match_score": 0.475 - }, - "D06P": { - "topic_id": "https://openalex.org/T11511", - "topic_display_name": "Dyeing and Modifying Textile Fibers", - "ipc_label": "DYEING OR PRINTING TEXTILESDYEING LEATHER, FURS OR SOLID MACROMOLECULAR SUBSTANCES IN ANY FORM", - "match_score": 0.372 - }, - "D10B": { - "topic_id": "https://openalex.org/T12078", - "topic_display_name": "Environmental remediation with nanomaterials", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBLASSES OF SECTION D, RELATING TO TEXTILES", - "match_score": 0.4 - }, - "D21B": { - "topic_id": "https://openalex.org/T11485", - "topic_display_name": "Gastrointestinal Tumor Research and Treatment", - "ipc_label": "FIBROUS RAW MATERIALS OR THEIR MECHANICAL TREATMENT", - "match_score": 0.562 - }, - "D21D": { - "topic_id": "https://openalex.org/T11071", - "topic_display_name": "Treatment of Major Depression", - "ipc_label": "TREATMENT OF THE MATERIALS BEFORE PASSING TO THE PAPER-MAKING MACHINE", - "match_score": 0.469 - }, - "D99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "E01F": { - "topic_id": "https://openalex.org/T14390", - "topic_display_name": "Real estate and construction management", - "ipc_label": "ADDITIONAL WORK, SUCH AS EQUIPPING ROADS OR THE CONSTRUCTION OF PLATFORMS, HELICOPTER LANDING STAGES, SIGNS, SNOW FENCES, OR THE LIKE", - "match_score": 0.36 - }, - "E02B": { - "topic_id": "https://openalex.org/T12907", - "topic_display_name": "Mechanical Engineering and Vibrations Research", - "ipc_label": "HYDRAULIC ENGINEERING ship-lifting E02C; dredging E02F", - "match_score": 0.5 - }, - "E02C": { - "topic_id": "https://openalex.org/T13253", - "topic_display_name": "Chemical Reactions and Mechanisms", - "ipc_label": "SHIP-LIFTING DEVICES OR MECHANISMS", - "match_score": 0.567 - }, - "E02D": { - "topic_id": "https://openalex.org/T12233", - "topic_display_name": "Geotechnical Engineering and Underground Structures", - "ipc_label": "FOUNDATIONSEXCAVATIONSEMBANKMENTS specially adapted for hydraulic engineering E02BUNDERGROUND OR UNDERWATER STRUCTURES tunnels, tunnelling, mining E21", - "match_score": 0.408 - }, - "E02F": { - "topic_id": "https://openalex.org/T13027", - "topic_display_name": "Applied Advanced Technologies", - "ipc_label": "DREDGINGSOIL-SHIFTING winning peat E21C49/00", - "match_score": 0.381 - }, - "E03D": { - "topic_id": "https://openalex.org/T14249", - "topic_display_name": "Water Quality Monitoring and Analysis", - "ipc_label": "WATER-CLOSETS OR URINALS WITH FLUSHING DEVICESFLUSHING VALVES THEREFOR", - "match_score": 0.355 - }, - "E03F": { - "topic_id": "https://openalex.org/T13675", - "topic_display_name": "Diffusion Coefficients in Liquids", - "ipc_label": "SEWERSCESSPOOLS", - "match_score": 0.444 - }, - "E05B": { - "topic_id": "https://openalex.org/T10859", - "topic_display_name": "Polymer Surface Interaction Studies", - "ipc_label": "LOCKSACCESSORIES THEREFORHANDCUFFS", - "match_score": 0.452 - }, - "E21C": { - "topic_id": "https://openalex.org/T11933", - "topic_display_name": "Mining and Resource Management", - "ipc_label": "MINING OR QUARRYING", - "match_score": 0.531 - }, - "E21F": { - "topic_id": "https://openalex.org/T10570", - "topic_display_name": "Drug Transport and Resistance Mechanisms", - "ipc_label": "SAFETY DEVICES, TRANSPORT, FILLING-UP, RESCUE, VENTILATION, OR DRAINING IN OR OF MINES OR TUNNELS", - "match_score": 0.38 - }, - "E99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "F01L": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "CYCLICALLY OPERATING VALVES FOR MACHINES OR ENGINES", - "match_score": 0.478 - }, - "F02F": { - "topic_id": "https://openalex.org/T10117", - "topic_display_name": "Advanced Combustion Engine Technologies", - "ipc_label": "CYLINDERS, PISTONS OR CASINGS, FOR COMBUSTION ENGINESARRANGEMENTS OF SEALINGS IN COMBUSTION ENGINES", - "match_score": 0.406 - }, - "F02M": { - "topic_id": "https://openalex.org/T13917", - "topic_display_name": "Engineering and Material Science Research", - "ipc_label": "SUPPLYING COMBUSTION ENGINES IN GENERAL WITH COMBUSTIBLE MIXTURES OR CONSTITUENTS THEREOF", - "match_score": 0.385 - }, - "F02N": { - "topic_id": "https://openalex.org/T10117", - "topic_display_name": "Advanced Combustion Engine Technologies", - "ipc_label": "STARTING OF COMBUSTION ENGINESSTARTING AIDS FOR SUCH ENGINES, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.441 - }, - "F03D": { - "topic_id": "https://openalex.org/T10504", - "topic_display_name": "Sensorless Control of Electric Motors", - "ipc_label": "WIND MOTORS", - "match_score": 0.5 - }, - "F03H": { - "topic_id": "https://openalex.org/T12661", - "topic_display_name": "Iterative Methods for Nonlinear Equations", - "ipc_label": "PRODUCING A REACTIVE PROPULSIVE THRUST, NOT OTHERWISE PROVIDED FOR from combustion products F02K", - "match_score": 0.35 - }, - "F16C": { - "topic_id": "https://openalex.org/T14144", - "topic_display_name": "Neurological Disease Mechanisms and Treatments", - "ipc_label": "SHAFTSFLEXIBLE SHAFTSELEMENTS OR CRANKSHAFT MECHANISMSROTARY BODIES OTHER THAN GEARING ELEMENTSBEARINGS", - "match_score": 0.376 - }, - "F16D": { - "topic_id": "https://openalex.org/T12240", - "topic_display_name": "Nanomaterials for catalytic reactions", - "ipc_label": "COUPLINGS FOR TRANSMITTING ROTATIONCLUTCHESBRAKES", - "match_score": 0.465 - }, - "F16F": { - "topic_id": "https://openalex.org/T10030", - "topic_display_name": "Electrocatalysts for Energy Conversion", - "ipc_label": "SPRINGSSHOCK-ABSORBERSMEANS FOR DAMPING VIBRATION", - "match_score": 0.437 - }, - "F16H": { - "topic_id": "https://openalex.org/T14252", - "topic_display_name": "Water and Wastewater Treatment", - "ipc_label": "GEARING", - "match_score": 0.667 - }, - "F16J": { - "topic_id": "https://openalex.org/T14353", - "topic_display_name": "Wireless Sensor Networks for Data Analysis", - "ipc_label": "PISTONS specially adapted for dampers F16F9/32CYLINDERSSEALINGS", - "match_score": 0.4 - }, - "F16L": { - "topic_id": "https://openalex.org/T11343", - "topic_display_name": "Power Transformer Diagnostics and Insulation", - "ipc_label": "PIPESJOINTS OR FITTINGS FOR PIPESSUPPORTS FOR PIPES, CABLES OR PROTECTIVE TUBINGMEANS FOR THERMAL INSULATION IN GENERAL", - "match_score": 0.356 - }, - "F16N": { - "topic_id": "https://openalex.org/T14075", - "topic_display_name": "Psychodrama and Leishmaniasis Studies", - "ipc_label": "LUBRICATING", - "match_score": 0.6 - }, - "F16P": { - "topic_id": "https://openalex.org/T11317", - "topic_display_name": "Fire dynamics and safety research", - "ipc_label": "SAFETY DEVICES IN GENERAL; SAFETY DEVICES FOR PRESSES", - "match_score": 0.488 - }, - "F16S": { - "topic_id": "https://openalex.org/T10915", - "topic_display_name": "Trace Elements in Health", - "ipc_label": "CONSTRUCTIONAL ELEMENTS IN GENERALSTRUCTURES BUILT-UP FROM SUCH ELEMENTS, IN GENERAL", - "match_score": 0.389 - }, - "F21L": { - "topic_id": "https://openalex.org/T13000", - "topic_display_name": "World Systems and Global Transformations", - "ipc_label": "LIGHTING DEVICES OR SYSTEMS THEREOF, BEING PORTABLE OR SPECIALLY ADAPTED FOR TRANSPORTATION", - "match_score": 0.427 - }, - "F21W": { - "topic_id": "https://openalex.org/T13257", - "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", - "ipc_label": "INDEXING SCHEME ASSOCIATED WITH SUBCLASSES F21K, F21L, F21S and F21V, RELATING TO USES OR APPLICATIONS OF LIGHTING DEVICES OR SYSTEMS", - "match_score": 0.383 - }, - "F22G": { - "topic_id": "https://openalex.org/T13960", - "topic_display_name": "Dietetics, Nutrition, and Education", - "ipc_label": "SUPERHEATING OF STEAM steam separating arrangements in boilers F22B37/26", - "match_score": 0.416 - }, - "F23D": { - "topic_id": "https://openalex.org/T11069", - "topic_display_name": "Testicular diseases and treatments", - "ipc_label": "BURNERS", - "match_score": 0.571 - }, - "F23G": { - "topic_id": "https://openalex.org/T14505", - "topic_display_name": "Natural Products and Applications", - "ipc_label": "CREMATION FURNACESCONSUMING WASTE PRODUCTS BY COMBUSTION", - "match_score": 0.472 - }, - "F23K": { - "topic_id": "https://openalex.org/T10806", - "topic_display_name": "Energetic Materials and Combustion", - "ipc_label": "FEEDING FUEL TO COMBUSTION APPARATUS fuel feeders specially adapted for fluidised bed combustion apparatus F23C10/22", - "match_score": 0.373 - }, - "F24S": { - "topic_id": "https://openalex.org/T10108", - "topic_display_name": "Electoral Systems and Political Participation", - "ipc_label": "SOLAR HEAT COLLECTORSSOLAR HEAT SYSTEMS for producing mechanical power from solar energy F03G6/00", - "match_score": 0.423 - }, - "F24T": { - "topic_id": "https://openalex.org/T11225", - "topic_display_name": "Geothermal Energy Systems and Applications", - "ipc_label": "GEOTHERMAL COLLECTORSGEOTHERMAL SYSTEMS", - "match_score": 0.667 - }, - "F24V": { - "topic_id": "https://openalex.org/T10171", - "topic_display_name": "Biofuel production and bioconversion", - "ipc_label": "COLLECTION, PRODUCTION OR USE OF HEAT NOT OTHERWISE PROVIDED FOR", - "match_score": 0.42 - }, - "F25B": { - "topic_id": "https://openalex.org/T13985", - "topic_display_name": "Enterprise Management and Information Systems", - "ipc_label": "REFRIGERATION MACHINES, PLANTS OR SYSTEMSCOMBINED HEATING AND REFRIGERATION SYSTEMSHEAT PUMP SYSTEMS", - "match_score": 0.414 - }, - "F25C": { - "topic_id": "https://openalex.org/T12544", - "topic_display_name": "Working Capital and Financial Performance", - "ipc_label": "PRODUCING, WORKING OR HANDLING ICE", - "match_score": 0.453 - }, - "F27M": { - "topic_id": "https://openalex.org/T10055", - "topic_display_name": "Diverse Aspects of Tourism Research", - "ipc_label": "INDEXING SCHEME RELATING TO ASPECTS OF THE CHARGES OR FURNACES, KILNS, OVENS OR RETORTS", - "match_score": 0.41 - }, - "F28F": { - "topic_id": "https://openalex.org/T11655", - "topic_display_name": "HIV-related health complications and treatments", - "ipc_label": "DETAILS OF HEAT-EXCHANGE AND HEAT-TRANSFER APPARATUS, OF GENERAL APPLICATION water and air traps, air venting F16", - "match_score": 0.412 - }, - "F41A": { - "topic_id": "https://openalex.org/T13468", - "topic_display_name": "Educational Research and Science Teaching", - "ipc_label": "FUNCTIONAL FEATURES OR DETAILS COMMON TO BOTH SMALLARMS AND ORDNANCE, e.g. CANNONSMOUNTINGS FOR SMALLARMS OR ORDNANCE", - "match_score": 0.367 - }, - "F41G": { - "topic_id": "https://openalex.org/T13049", - "topic_display_name": "Surface Roughness and Optical Measurements", - "ipc_label": "WEAPON SIGHTSAIMING optical aspects thereof G02B", - "match_score": 0.467 - }, - "F99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "G01F": { - "topic_id": "https://openalex.org/T10836", - "topic_display_name": "Metabolomics and Mass Spectrometry Studies", - "ipc_label": "MEASURING VOLUME, VOLUME FLOW, MASS FLOW OR LIQUID LEVELMETERING BY VOLUME", - "match_score": 0.379 - }, - "G01G": { - "topic_id": "https://openalex.org/T13960", - "topic_display_name": "Dietetics, Nutrition, and Education", - "ipc_label": "WEIGHING sorting by weighing B07C5/16", - "match_score": 0.364 - }, - "G01H": { - "topic_id": "https://openalex.org/T10386", - "topic_display_name": "Microstructure and Mechanical Properties of Steels", - "ipc_label": "MEASUREMENT OF MECHANICAL VIBRATIONS OR ULTRASONIC, SONIC OR INFRASONIC WAVES", - "match_score": 0.425 - }, - "G01L": { - "topic_id": "https://openalex.org/T10386", - "topic_display_name": "Microstructure and Mechanical Properties of Steels", - "ipc_label": "MEASURING FORCE, STRESS, TORQUE, WORK, MECHANICAL POWER, MECHANICAL EFFICIENCY, OR FLUID PRESSURE weighing G01G", - "match_score": 0.385 - }, - "G01Q": { - "topic_id": "https://openalex.org/T10801", - "topic_display_name": "Synthetic Aperture Radar (SAR) Applications and Techniques", - "ipc_label": "SCANNING-PROBE TECHNIQUES OR APPARATUSAPPLICATIONS OF SCANNING-PROBE TECHNIQUES, e.g. SCANNING PROBE MICROSCOPY [SPM]", - "match_score": 0.389 - }, - "G01R": { - "topic_id": "https://openalex.org/T10614", - "topic_display_name": "Transcranial Magnetic Stimulation Studies", - "ipc_label": "MEASURING ELECTRIC VARIABLESMEASURING MAGNETIC VARIABLES indicating correct tuning of resonant circuits H03J3/12", - "match_score": 0.379 - }, - "G02B": { - "topic_id": "https://openalex.org/T12391", - "topic_display_name": "Artificial Immune Systems Applications", - "ipc_label": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS", - "match_score": 0.579 - }, - "G04D": { - "topic_id": "https://openalex.org/T13583", - "topic_display_name": "Jury Decision Making Processes", - "ipc_label": "APPARATUS OR TOOLS SPECIALLY DESIGNED FOR MAKING OR MAINTAINING CLOCKS OR WATCHES", - "match_score": 0.378 - }, - "G04F": { - "topic_id": "https://openalex.org/T13293", - "topic_display_name": "Engineering and Test Systems", - "ipc_label": "TIME-INTERVAL MEASURING measuring pulse characteristics G01R, e.g. G01R29/02; in radar or like systems G01S", - "match_score": 0.37 - }, - "G04G": { - "topic_id": "https://openalex.org/T10350", - "topic_display_name": "Electronic Health Records Systems", - "ipc_label": "ELECTRONIC TIME-PIECES", - "match_score": 0.582 - }, - "G04R": { - "topic_id": "https://openalex.org/T12810", - "topic_display_name": "Real-time simulation and control systems", - "ipc_label": "RADIO-CONTROLLED TIME-PIECES", - "match_score": 0.441 - }, - "G05D": { - "topic_id": "https://openalex.org/T10504", - "topic_display_name": "Sensorless Control of Electric Motors", - "ipc_label": "SYSTEMS FOR CONTROLLING OR REGULATING NON-ELECTRIC VARIABLES", - "match_score": 0.536 - }, - "G06C": { - "topic_id": "https://openalex.org/T13155", - "topic_display_name": "Digital Communication and Language", - "ipc_label": "DIGITAL COMPUTERS IN WHICH ALL THE COMPUTATION IS EFFECTED MECHANICALLY score computers for card games A63F1/18", - "match_score": 0.372 - }, - "G06D": { - "topic_id": "https://openalex.org/T12923", - "topic_display_name": "Digital Image Processing Techniques", - "ipc_label": "DIGITAL FLUID-PRESSURE COMPUTING DEVICES", - "match_score": 0.587 - }, - "G06F": { - "topic_id": "https://openalex.org/T13093", - "topic_display_name": "Electric Power Systems and Control", - "ipc_label": "ELECTRIC DIGITAL DATA PROCESSING computer systems based on specific computational models G06N", - "match_score": 0.472 - }, - "G06G": { - "topic_id": "https://openalex.org/T11429", - "topic_display_name": "Semiconductor Lasers and Optical Devices", - "ipc_label": "ANALOGUE COMPUTERS analogue optical computing devices G06E3/00", - "match_score": 0.529 - }, - "G06K": { - "topic_id": "https://openalex.org/T10627", - "topic_display_name": "Advanced Image and Video Retrieval Techniques", - "ipc_label": "GRAPHICAL DATA READING image or video recognition or understanding G06VPRESENTATION OF DATARECORD CARRIERSHANDLING RECORD CARRIERS", - "match_score": 0.354 - }, - "G06N": { - "topic_id": "https://openalex.org/T13806", - "topic_display_name": "Mathematical and Computational Methods", - "ipc_label": "COMPUTING ARRANGEMENTS BASED ON SPECIFIC COMPUTATIONAL MODELS", - "match_score": 0.525 - }, - "G06T": { - "topic_id": "https://openalex.org/T14339", - "topic_display_name": "Image Processing and 3D Reconstruction", - "ipc_label": "IMAGE DATA PROCESSING OR GENERATION, IN GENERAL", - "match_score": 0.541 - }, - "G06V": { - "topic_id": "https://openalex.org/T13579", - "topic_display_name": "Image and Video Stabilization", - "ipc_label": "IMAGE OR VIDEO RECOGNITION OR UNDERSTANDING", - "match_score": 0.75 - }, - "G07G": { - "topic_id": "https://openalex.org/T13321", - "topic_display_name": "Radio, Podcasts, and Digital Media", - "ipc_label": "REGISTERING THE RECEIPT OF CASH, VALUABLES, OR TOKENS digital computing in general G06C, G06F", - "match_score": 0.378 - }, - "G08B": { - "topic_id": "https://openalex.org/T11902", - "topic_display_name": "Intelligent Tutoring Systems and Adaptive Learning", - "ipc_label": "SIGNALLING OR CALLING SYSTEMSORDER TELEGRAPHSALARM SYSTEMS", - "match_score": 0.5 - }, - "G09F": { - "topic_id": "https://openalex.org/T14032", - "topic_display_name": "History and International Relations", - "ipc_label": "DISPLAYINGADVERTISINGSIGNSLABELS OR NAME-PLATESSEALS", - "match_score": 0.391 - }, - "G10L": { - "topic_id": "https://openalex.org/T13244", - "topic_display_name": "Analysis of environmental and stochastic processes", - "ipc_label": "SPEECH ANALYSIS OR SYNTHESISSPEECH RECOGNITIONSPEECH OR VOICE PROCESSINGSPEECH OR AUDIO CODING OR DECODING", - "match_score": 0.359 - }, - "G11C": { - "topic_id": "https://openalex.org/T10472", - "topic_display_name": "Semiconductor materials and devices", - "ipc_label": "STATIC STORES semiconductor memory devices H10B", - "match_score": 0.61 - }, - "G16C": { - "topic_id": "https://openalex.org/T10192", - "topic_display_name": "Catalytic Processes in Materials Science", - "ipc_label": "COMPUTATIONAL CHEMISTRYCHEMOINFORMATICSCOMPUTATIONAL MATERIALS SCIENCE", - "match_score": 0.527 - }, - "G16H": { - "topic_id": "https://openalex.org/T11773", - "topic_display_name": "Healthcare Operations and Scheduling Optimization", - "ipc_label": "HEALTHCARE INFORMATICS, i.e. INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR THE HANDLING OR PROCESSING OF MEDICAL OR HEALTHCARE DATA", - "match_score": 0.384 - }, - "G16Y": { - "topic_id": "https://openalex.org/T13952", - "topic_display_name": "Information Technology and Learning", - "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]", - "match_score": 0.508 - }, - "G16Z": { - "topic_id": "https://openalex.org/T12734", - "topic_display_name": "Information Systems and Technology Applications", - "ipc_label": "INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS, NOT OTHERWISE PROVIDED FOR", - "match_score": 0.456 - }, - "G21B": { - "topic_id": "https://openalex.org/T10592", - "topic_display_name": "Fusion materials and technologies", - "ipc_label": "FUSION REACTORS uncontrolled reactors G21J", - "match_score": 0.48 - }, - "G21C": { - "topic_id": "https://openalex.org/T10808", - "topic_display_name": "Electric and Hybrid Vehicle Technologies", - "ipc_label": "NUCLEAR REACTORS fusion reactors, hybrid fission-fusion reactors G21B; nuclear explosives G21J", - "match_score": 0.388 - }, - "G21D": { - "topic_id": "https://openalex.org/T12295", - "topic_display_name": "Foucault, Power, and Ethics", - "ipc_label": "NUCLEAR POWER PLANT", - "match_score": 0.565 - }, - "G21J": { - "topic_id": "https://openalex.org/T12405", - "topic_display_name": "Characterization and Applications of Magnetic Nanoparticles", - "ipc_label": "NUCLEAR EXPLOSIVESAPPLICATIONS THEREOF electric or magnetic analogue computers, e.g. simulators, for nuclear physics G06G7/54", - "match_score": 0.413 - }, - "G99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "H01C": { - "topic_id": "https://openalex.org/T12454", - "topic_display_name": "European Political History Analysis", - "ipc_label": "RESISTORS", - "match_score": 0.625 - }, - "H01J": { - "topic_id": "https://openalex.org/T12495", - "topic_display_name": "Electrostatic Discharge in Electronics", - "ipc_label": "ELECTRIC DISCHARGE TUBES OR DISCHARGE LAMPS spark-gaps H01T; arc lamps with consumable electrodes H05B; particle accelerators H05H", - "match_score": 0.381 - }, - "H01M": { - "topic_id": "https://openalex.org/T12495", - "topic_display_name": "Electrostatic Discharge in Electronics", - "ipc_label": "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE DIRECT CONVERSION OF CHEMICAL ENERGY INTO ELECTRICAL ENERGY", - "match_score": 0.383 - }, - "H01P": { - "topic_id": "https://openalex.org/T11429", - "topic_display_name": "Semiconductor Lasers and Optical Devices", - "ipc_label": "WAVEGUIDESRESONATORS, LINES, OR OTHER DEVICES OF THE WAVEGUIDE TYPE operating at optical frequencies G02B", - "match_score": 0.4 - }, - "H01Q": { - "topic_id": "https://openalex.org/T10579", - "topic_display_name": "Cognitive Radio Networks and Spectrum Sensing", - "ipc_label": "ANTENNAS, i.e. RADIO AERIALS radiators or antennas for microwave heating H05B6/72", - "match_score": 0.397 - }, - "H02B": { - "topic_id": "https://openalex.org/T10968", - "topic_display_name": "Statistical Distribution Estimation and Applications", - "ipc_label": "BOARDS, SUBSTATIONS OR SWITCHING ARRANGEMENTS FOR THE SUPPLY OR DISTRIBUTION OF ELECTRIC POWER", - "match_score": 0.411 - }, - "H02G": { - "topic_id": "https://openalex.org/T10607", - "topic_display_name": "Magnetic and transport properties of perovskites and related materials", - "ipc_label": "INSTALLATION OF ELECTRIC CABLES OR LINES, OR OF COMBINED OPTICAL AND ELECTRIC CABLES OR LINES", - "match_score": 0.444 - }, - "H02J": { - "topic_id": "https://openalex.org/T12111", - "topic_display_name": "Industrial Vision Systems and Defect Detection", - "ipc_label": "CIRCUIT ARRANGEMENTS OR SYSTEMS FOR SUPPLYING OR DISTRIBUTING ELECTRIC POWERSYSTEMS FOR STORING ELECTRIC ENERGY", - "match_score": 0.369 - }, - "H02N": { - "topic_id": "https://openalex.org/T10768", - "topic_display_name": "Electric Vehicles and Infrastructure", - "ipc_label": "ELECTRIC MACHINES NOT OTHERWISE PROVIDED FOR", - "match_score": 0.475 - }, - "H03C": { - "topic_id": "https://openalex.org/T10030", - "topic_display_name": "Electrocatalysts for Energy Conversion", - "ipc_label": "MODULATION masers or lasers H01S; coding, decoding or code conversion H03M", - "match_score": 0.429 - }, - "H03G": { - "topic_id": "https://openalex.org/T13924", - "topic_display_name": "Internet of Things and Social Network Interactions", - "ipc_label": "CONTROL OF AMPLIFICATION impedance networks, e.g. attenuators, H03H; control of transmission in lines H04B3/04", - "match_score": 0.375 - }, - "H03J": { - "topic_id": "https://openalex.org/T14117", - "topic_display_name": "Integrated Circuits and Semiconductor Failure Analysis", - "ipc_label": "TUNING RESONANT CIRCUITSSELECTING RESONANT CIRCUITS", - "match_score": 0.476 - }, - "H03L": { - "topic_id": "https://openalex.org/T13257", - "topic_display_name": "Advanced Control and Stabilization in Aerospace Systems", - "ipc_label": "AUTOMATIC CONTROL, STARTING, SYNCHRONISATION, OR STABILISATION OF GENERATORS OF ELECTRONIC OSCILLATIONS OR PULSES of dynamo-electric generators H02P", - "match_score": 0.355 - }, - "H04B": { - "topic_id": "https://openalex.org/T12804", - "topic_display_name": "Thermal Analysis in Power Transmission", - "ipc_label": "TRANSMISSION", - "match_score": 1.0 - }, - "H04H": { - "topic_id": "https://openalex.org/T12593", - "topic_display_name": "Communication in Education and Healthcare", - "ipc_label": "BROADCAST COMMUNICATION multiplex communication H04J; pictorial communication aspects of broadcast systems H04N", - "match_score": 0.408 - }, - "H04K": { - "topic_id": "https://openalex.org/T13317", - "topic_display_name": "Media, Communication, and Education", - "ipc_label": "SECRET COMMUNICATIONJAMMING OF COMMUNICATION", - "match_score": 0.633 - }, - "H04L": { - "topic_id": "https://openalex.org/T12607", - "topic_display_name": "Personal Information Management and User Behavior", - "ipc_label": "TRANSMISSION OF DIGITAL INFORMATION, e.g. TELEGRAPHIC COMMUNICATION arrangements common to telegraphic and telephonic communication H04M", - "match_score": 0.422 - }, - "H04M": { - "topic_id": "https://openalex.org/T13905", - "topic_display_name": "Telecommunications and Broadcasting Technologies", - "ipc_label": "TELEPHONIC COMMUNICATION circuits for controlling other apparatus via a telephone cable and not involving telephone switching apparatus G08", - "match_score": 0.374 - }, - "H04N": { - "topic_id": "https://openalex.org/T13317", - "topic_display_name": "Media, Communication, and Education", - "ipc_label": "PICTORIAL COMMUNICATION, e.g. TELEVISION", - "match_score": 0.613 - }, - "H04Q": { - "topic_id": "https://openalex.org/T10575", - "topic_display_name": "Wireless Communication Networks Research", - "ipc_label": "SELECTING switches, relays, selectors H01H; wireless communication networks H04W", - "match_score": 0.55 - }, - "H04S": { - "topic_id": "https://openalex.org/T11575", - "topic_display_name": "Nonlinear Photonic Systems", - "ipc_label": "STEREOPHONIC SYSTEMS", - "match_score": 0.696 - }, - "H04T": { - "topic_id": "https://openalex.org/T11121", - "topic_display_name": "Public Relations and Crisis Communication", - "ipc_label": "INDEXING SCHEME RELATING TO STANDARDS FOR ELECTRIC COMMUNICATION TECHNIQUE CLASS H04", - "match_score": 0.512 - }, - "H04W": { - "topic_id": "https://openalex.org/T10575", - "topic_display_name": "Wireless Communication Networks Research", - "ipc_label": "WIRELESS COMMUNICATION NETWORKS broadcast communication H04H; communication systems using wireless links for non-selective communication, e.g. wireless extensions H04M1/72", - "match_score": 0.36 - }, - "H05B": { - "topic_id": "https://openalex.org/T13093", - "topic_display_name": "Electric Power Systems and Control", - "ipc_label": "ELECTRIC HEATINGELECTRIC LIGHT SOURCES NOT OTHERWISE PROVIDED FORCIRCUIT ARRANGEMENTS FOR ELECTRIC LIGHT SOURCES, IN GENERAL", - "match_score": 0.36 - }, - "H10B": { - "topic_id": "https://openalex.org/T10299", - "topic_display_name": "Photonic and Optical Devices", - "ipc_label": "ELECTRONIC MEMORY DEVICES", - "match_score": 0.667 - }, - "H10K": { - "topic_id": "https://openalex.org/T10045", - "topic_display_name": "Organic Electronics and Photovoltaics", - "ipc_label": "ORGANIC ELECTRIC SOLID-STATE DEVICES", - "match_score": 0.658 - }, - "H10N": { - "topic_id": "https://openalex.org/T10768", - "topic_display_name": "Electric Vehicles and Infrastructure", - "ipc_label": "ELECTRIC SOLID-STATE DEVICES NOT OTHERWISE PROVIDED FOR", - "match_score": 0.44 - }, - "H99Z": { - "topic_id": "https://openalex.org/T12682", - "topic_display_name": "Smart Materials for Construction", - "ipc_label": "SUBJECT MATTER NOT OTHERWISE PROVIDED FOR IN THIS SECTION", - "match_score": 0.494 - }, - "Y02A": { - "topic_id": "https://openalex.org/T10895", - "topic_display_name": "Species Distribution and Climate Change", - "ipc_label": "TECHNOLOGIES FOR ADAPTATION TO CLIMATE CHANGE", - "match_score": 0.643 - }, - "Y02B": { - "topic_id": "https://openalex.org/T13734", - "topic_display_name": "Advanced Computational Techniques and Applications", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO BUILDINGS, e.g. HOUSING, HOUSE APPLIANCES OR RELATED END-USER APPLICATIONS", - "match_score": 0.425 - }, - "Y02C": { - "topic_id": "https://openalex.org/T10945", - "topic_display_name": "Lysosomal Storage Disorders Research", - "ipc_label": "CAPTURE, STORAGE, SEQUESTRATION OR DISPOSAL OF GREENHOUSE GASES [GHG]", - "match_score": 0.419 - }, - "Y02P": { - "topic_id": "https://openalex.org/T11488", - "topic_display_name": "Climate Change Communication and Perception", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES IN THE PRODUCTION OR PROCESSING OF GOODS", - "match_score": 0.525 - }, - "Y02T": { - "topic_id": "https://openalex.org/T11488", - "topic_display_name": "Climate Change Communication and Perception", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO TRANSPORTATION", - "match_score": 0.598 - }, - "Y02W": { - "topic_id": "https://openalex.org/T11404", - "topic_display_name": "Irrigation Practices and Water Management", - "ipc_label": "CLIMATE CHANGE MITIGATION TECHNOLOGIES RELATED TO WASTEWATER TREATMENT OR WASTE MANAGEMENT", - "match_score": 0.504 - }, - "Y10S": { - "topic_id": "https://openalex.org/T13332", - "topic_display_name": "Historical Studies on Reproduction, Gender, Health, and Societal Changes", - "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER USPC CROSS-REFERENCE ART COLLECTIONS [XRACs] AND DIGESTS", - "match_score": 0.412 - }, - "Y10T": { - "topic_id": "https://openalex.org/T10885", - "topic_display_name": "Gene expression and cancer classification", - "ipc_label": "TECHNICAL SUBJECTS COVERED BY FORMER US CLASSIFICATION", - "match_score": 0.484 - } - }, - "group": {}, - "subgroup": {} -} \ No newline at end of file diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index bb40f8f9..7b88a2f8 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -26,6 +26,7 @@ from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router from inse.university_ranking.service import router as university_ranking_router from inse.keywords.service import router as keywords_service_router +from inse.patents.keywords.service import router as keywords_patents_router # caching from inse.middleware.etag_cache import ETagCacheMiddleware @@ -90,6 +91,7 @@ app.include_router(university_ranking_router) app.include_router(projects_router) app.include_router(patents_all_router) app.include_router(keywords_service_router) +app.include_router(keywords_patents_router) app.include_router(service_router) diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 6daeabe4..28d95c6e 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -3,9 +3,15 @@ from __future__ import annotations import asyncio import logging +import math +import re import httpx +from inse.patents.authors.ipc_openalex_mapping import ( + MappedOpenAlexTopic, + normalize_openalex_id, +) from inse.patents.common import model from inse.patents.common.elastic_search_client import ( BasePatentSearchClient, @@ -16,8 +22,12 @@ from inse.patents.common.parsing import ( enrich_patents_classifications, parse_epo_hits, parse_uspto_hits, + patent_map_key, +) +from inse.patents.ipc_lookup import ( + extract_ipc_symbol, + parse_ipc_symbol, ) -from inse.patents.ipc_lookup import extract_ipc_symbol from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( KeywordPatentMatch, @@ -26,19 +36,100 @@ from inse.patents.keywords.model import ( PatentsByKeywordsResponse, ) from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup -from inse.patents.keywords.search_queries import ( - IpcPatentSearchQueries, - _search_terms_for_symbol, -) -from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol +from inse.patents.keywords.search_queries import IpcPatentSearchQueries +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol +from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver logger = logging.getLogger(__name__) _MAX_PATENTS = 100 -_MAX_IPC_CODES = 40 -_MAX_PATENT_SEARCH_TERMS = 12 -_MIN_IPC_MATCH_SCORE = 0.45 -_MIN_PATENT_MATCH_SCORE = 0.35 +_MAX_IPC_CODES = 20 +_MAX_IPC_CODES_PER_KEYWORD = 2 +_MAX_PATENT_SEARCH_TERMS = 10 +_MAX_SEARCH_KEYWORDS = 10 +_MIN_KEYWORD_RELEVANCE = 0.0 +_MIN_IPC_MATCH_SCORE = 0.65 +_MIN_PATENT_MATCH_SCORE = 0.50 +_SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"}) +# Soft field overlap for natural-science / engineering patent domains. +_SOFT_MATCH_FIELD_NAMES = frozenset( + { + "engineering", + "computer science", + "physical sciences", + "physics and astronomy", + "materials science", + "environmental science", + "chemical engineering", + "chemistry", + "earth and planetary sciences", + "medicine", + "biochemistry, genetics and molecular biology", + "immunology and microbiology", + } +) +_PREFERRED_KEYWORD_LEVELS = frozenset({"coarse", "fine", "custom"}) +_NON_TECHNICAL_FIELD_NAMES = frozenset( + { + "social sciences", + "arts and humanities", + "law", + "business, management and accounting", + } +) +_COMPATIBLE_FIELDS: dict[str, frozenset[str]] = { + "chemistry": frozenset( + {"chemistry", "chemical engineering", "materials science"} + ), + "chemical engineering": frozenset( + {"chemical engineering", "chemistry", "materials science"} + ), + "materials science": frozenset( + {"materials science", "chemistry", "chemical engineering", "engineering"} + ), + "computer science": frozenset({"computer science", "engineering"}), + "engineering": frozenset( + {"engineering", "computer science", "materials science"} + ), + "physical sciences": frozenset( + {"physical sciences", "physics and astronomy", "chemistry", "materials science"} + ), + "physics and astronomy": frozenset( + {"physics and astronomy", "physical sciences", "materials science"} + ), + "biochemistry, genetics and molecular biology": frozenset( + { + "biochemistry, genetics and molecular biology", + "chemistry", + "medicine", + } + ), + "medicine": frozenset( + { + "medicine", + "biochemistry, genetics and molecular biology", + "immunology and microbiology", + } + ), +} +_TEXT_STOPWORDS = frozenset( + { + "and", + "the", + "of", + "in", + "for", + "und", + "der", + "die", + "das", + "von", + "medicine", + "medical", + "science", + "sciences", + } +) def _ipc_section(symbol: str) -> str: @@ -57,18 +148,26 @@ def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> s return {section for section, _ in ranked[:limit]} +def _prefer_searchable_ipc_levels(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: + searchable = [ + match for match in ipc_matches if match.ipc_level in _SEARCHABLE_IPC_LEVELS + ] + return searchable if searchable else ipc_matches + + def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: if not ipc_matches: return [] + ipc_matches = _prefer_searchable_ipc_levels(ipc_matches) ranked = sorted(ipc_matches, key=lambda match: match.match_score, reverse=True) strong = [ match for match in ranked - if match.match_score >= _MIN_IPC_MATCH_SCORE or match.match_type == "heuristic" + if match.match_score >= _MIN_IPC_MATCH_SCORE ] if not strong: - strong = ranked[:8] + return [] dominant_sections = _dominant_ipc_sections(strong) filtered: list[IpcCodeMatch] = [] @@ -77,10 +176,6 @@ def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcC key = (match.ipc_level, match.ipc_symbol) if key in seen: continue - if match.match_type == "heuristic": - filtered.append(match) - seen.add(key) - continue if match.match_score >= 0.8: filtered.append(match) seen.add(key) @@ -89,215 +184,420 @@ def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcC filtered.append(match) seen.add(key) - return filtered or strong[:12] + return filtered -def _active_heuristic_prefixes(ipc_matches: list[IpcCodeMatch]) -> set[str]: - prefixes: set[str] = set() - for match in ipc_matches: - if match.match_type != "heuristic": - continue - symbol = normalize_symbol(match.ipc_symbol) - if not symbol: - continue - for prefix in ( - "A61", - "B01", - "C01", - "C07", - "C08", - "C09", - "C10", - "C12", - "G01N", - "G06", - "B60", - "F02", - ): - if symbol.startswith(prefix): - prefixes.add(prefix) - return prefixes +def _limit_matches_per_keyword( + matches: list[IpcCodeMatch], + limit: int = _MAX_IPC_CODES_PER_KEYWORD, +) -> list[IpcCodeMatch]: + grouped: dict[str, list[IpcCodeMatch]] = {} + for match in matches: + grouped.setdefault(match.source_keyword.casefold(), []).append(match) + result: list[IpcCodeMatch] = [] + for keyword_matches in grouped.values(): + keyword_matches.sort(key=lambda match: match.match_score, reverse=True) + result.extend(keyword_matches[:limit]) -def _symbol_matches_heuristic_prefixes(symbol: str, prefixes: set[str]) -> bool: - normalized = normalize_symbol(symbol) - return any(normalized.startswith(prefix) for prefix in prefixes) - - -def _ipc_search_domain(symbol: str) -> str: - normalized = normalize_symbol(symbol) - if normalized.startswith("A61"): - return "medicine" - if ( - normalized.startswith("C") - or normalized.startswith("B01") - or normalized.startswith("G01N") - ): - return "chemistry" - if normalized.startswith("B60") or normalized.startswith("F02"): - return "automotive" - if normalized.startswith("G06"): - return "cs_ai" - return "other" + return sorted(result, key=lambda match: match.match_score, reverse=True) def _term_from_ipc_match(match: IpcCodeMatch) -> str | None: - from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass + symbol = normalize_symbol(match.ipc_symbol) + if not symbol: + return None - return infer_subclass(normalize_symbol(match.ipc_symbol)) - - -def _interleave_ipc_matches( - matches: list[IpcCodeMatch], - *, - limit: int, -) -> list[IpcCodeMatch]: - from collections import defaultdict - - by_domain: dict[str, list[IpcCodeMatch]] = defaultdict(list) - for match in matches: - by_domain[_ipc_search_domain(match.ipc_symbol)].append(match) - - if len(by_domain) <= 1: - return matches[:limit] - - ordered: list[IpcCodeMatch] = [] - seen: set[tuple[str, str]] = set() - queues = list(by_domain.values()) - while len(ordered) < limit and queues: - progressed = False - for queue in list(queues): - if len(ordered) >= limit: - break - while queue: - match = queue.pop(0) - key = (match.ipc_level, match.ipc_symbol) - if key in seen: - continue - seen.add(key) - ordered.append(match) - progressed = True - break - queues = [queue for queue in queues if queue] - if not progressed: - break - return ordered - - -def _balanced_patent_matches( - scored: list[KeywordPatentMatch], - limit: int, -) -> list[KeywordPatentMatch]: - from collections import defaultdict - - by_domain: dict[str, list[KeywordPatentMatch]] = defaultdict(list) - for item in scored: - domain = ( - _ipc_search_domain(item.matched_ipc_symbols[0]) - if item.matched_ipc_symbols - else "other" - ) - by_domain[domain].append(item) - - if len(by_domain) <= 1: - return scored[:limit] - - ordered: list[KeywordPatentMatch] = [] - seen_ids: set[str] = set() - queues = list(by_domain.values()) - while len(ordered) < limit and queues: - progressed = False - for queue in list(queues): - if len(ordered) >= limit: - break - while queue: - item = queue.pop(0) - if item.patent.patent_id in seen_ids: - continue - seen_ids.add(item.patent.patent_id) - ordered.append(item) - progressed = True - break - queues = [queue for queue in queues if queue] - if not progressed: - break - return ordered + return infer_subclass(symbol) def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]: filtered = _filter_ipc_matches_for_search(ipc_matches) - active_prefixes = _active_heuristic_prefixes(ipc_matches) - if active_prefixes: - filtered = [ - match - for match in filtered - if _symbol_matches_heuristic_prefixes(match.ipc_symbol, active_prefixes) - ] - - filtered = _interleave_ipc_matches(filtered, limit=_MAX_PATENT_SEARCH_TERMS) + filtered = sorted(filtered, key=lambda match: match.match_score, reverse=True) terms: list[str] = [] seen: set[str] = set() for match in filtered: - subclass = _term_from_ipc_match(match) - if not subclass or subclass in seen: + if match.ipc_level not in _SEARCHABLE_IPC_LEVELS: continue - seen.add(subclass) - terms.append(subclass) + term = _term_from_ipc_match(match) + if not term or term in seen: + continue + seen.add(term) + terms.append(term) if len(terms) >= _MAX_PATENT_SEARCH_TERMS: break return terms -def _ipc_terms_overlap(patent_code: str, mapped_symbol: str) -> bool: - patent_terms = set( - _search_terms_for_symbol(extract_ipc_symbol(patent_code) or patent_code) - ) - mapped_terms = set(_search_terms_for_symbol(mapped_symbol)) - return bool(patent_terms & mapped_terms) +def _normalize_ipc_code(code: str) -> str: + extracted = extract_ipc_symbol(code) or code + return normalize_symbol(extracted) -def _patent_code_matches_symbol(patent_code: str, mapped_symbol: str) -> bool: - if _ipc_terms_overlap(patent_code, mapped_symbol): - return True - normalized_patent = normalize_symbol(extract_ipc_symbol(patent_code)) - normalized_mapped = normalize_symbol(mapped_symbol) +def _ipc_main_group(symbol: str) -> str | None: + parsed = parse_ipc_symbol(symbol) + if parsed is None or not parsed.main_group: + return None + + return normalize_symbol(parsed.main_group) + + +def _ipc_hierarchy_quality( + patent_code: str, + mapped_symbol: str, +) -> float: + normalized_patent = _normalize_ipc_code(patent_code) + normalized_mapped = _normalize_ipc_code(mapped_symbol) + if not normalized_patent or not normalized_mapped: + return 0.0 + + if normalized_patent == normalized_mapped: + return 1.0 + + patent_group = _ipc_main_group(normalized_patent) + mapped_group = _ipc_main_group(normalized_mapped) + + if patent_group and mapped_group and patent_group == mapped_group: + return 0.90 + + patent_subclass = infer_subclass(normalized_patent) + mapped_subclass = infer_subclass(normalized_mapped) + + if ( + patent_subclass + and mapped_subclass + and patent_subclass == mapped_subclass + ): + return 0.75 + + return 0.0 + + +def _ipc_hierarchy_level( + patent_code: str, + mapped_symbol: str, +) -> str | None: + quality = _ipc_hierarchy_quality(patent_code, mapped_symbol) + if quality >= 1.0: + return "exact" + if quality >= 0.90: + return "main_group" + if quality >= 0.75: + return "subclass" + return None + + +def _keyword_level(item: KeywordPatentSearchItem) -> str: + return (item.keyword_level or "").strip().casefold() + + +def _keyword_is_patent_searchable(item: KeywordPatentSearchItem) -> bool: + if not item.keyword.strip(): return False + + topic_id = normalize_openalex_id(item.topic_id) + if not topic_id: + return False + + field_name = _normalized_field_name(item.field_name) + if field_name in _NON_TECHNICAL_FIELD_NAMES: + return False + + return True + + +def _sort_and_limit_keywords( + items: list[KeywordPatentSearchItem], +) -> list[KeywordPatentSearchItem]: + ranked = sorted(items, key=lambda item: item.relevance_score, reverse=True) + return ranked[:_MAX_SEARCH_KEYWORDS] + + +def _filter_keywords_for_patent_search( + items: list[KeywordPatentSearchItem], +) -> list[KeywordPatentSearchItem]: + """Prefer coarse/fine/custom keywords; ignore broad when specifics exist.""" + searchable = [item for item in items if _keyword_is_patent_searchable(item)] + if not searchable: + return [] + + preferred = [ + item + for item in searchable + if _keyword_level(item) in _PREFERRED_KEYWORD_LEVELS + ] + if preferred: + return _sort_and_limit_keywords(preferred) + + non_broad = [ + item for item in searchable if _keyword_level(item) != "broad" + ] + if non_broad: + return _sort_and_limit_keywords(non_broad) + + return _sort_and_limit_keywords(searchable) + + +def _normalized_field_name(name: str | None) -> str: + return (name or "").strip().casefold() + + +def _patent_has_g06_code(patent: model.PatentEntry) -> bool: + for code in (*patent.ipc, *patent.cpc): + symbol = normalize_symbol(extract_ipc_symbol(code) or code) + if symbol.startswith("G06"): + return True + return False + + +def _compatible_patent_fields(keyword_field: str) -> frozenset[str]: + return _COMPATIBLE_FIELDS.get(keyword_field, frozenset({keyword_field})) + + +def _keyword_overlap_criteria( + items: list[KeywordPatentSearchItem], +) -> tuple[frozenset[str], frozenset[str], frozenset[str]]: + topic_ids: set[str] = set() + subfield_names: set[str] = set() + soft_field_names: set[str] = set() + for item in items: + topic_id = normalize_openalex_id(item.topic_id) + if topic_id: + topic_ids.add(topic_id) + subfield_name = (item.subfield_name or "").strip() + if subfield_name: + subfield_names.add(subfield_name.casefold()) + field_name = _normalized_field_name(item.field_name) + if field_name in _SOFT_MATCH_FIELD_NAMES: + soft_field_names.add(field_name) return ( - normalized_patent.startswith(normalized_mapped) - or normalized_mapped.startswith(normalized_patent) + frozenset(topic_ids), + frozenset(subfield_names), + frozenset(soft_field_names), + ) + + +def _topics_overlap_keywords( + patent_topics: list[MappedOpenAlexTopic], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + *, + patent: model.PatentEntry | None = None, +) -> bool: + if ( + not keyword_topic_ids + and not keyword_subfield_names + and not keyword_soft_field_names + ): + return True + + if not patent_topics: + return False + + patent_topic_ids = { + topic_id + for mapped in patent_topics + if (topic_id := normalize_openalex_id(mapped.topic_id)) + } + if keyword_topic_ids & patent_topic_ids: + return True + + patent_subfield_names = { + (mapped.subfield_name or "").strip().casefold() + for mapped in patent_topics + if (mapped.subfield_name or "").strip() + } + if keyword_subfield_names & patent_subfield_names: + return True + + if keyword_soft_field_names: + patent_field_names = { + _normalized_field_name(mapped.field_name) + for mapped in patent_topics + if mapped.field_name + } + for keyword_field in keyword_soft_field_names: + if patent_field_names & _compatible_patent_fields(keyword_field): + return True + if ( + patent is not None + and _patent_has_g06_code(patent) + and keyword_soft_field_names & {"engineering", "computer science"} + ): + return True + + return False + + +def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: + terms: list[str] = [] + seen: set[str] = set() + + for item in items: + for value in ( + item.keyword, + item.topic_display_name, + item.subfield_name, + ): + normalized = (value or "").strip().casefold() + if not normalized: + continue + + words = re.findall(r"[a-zäöüß]{4,}", normalized) + + for word in words: + if word in _TEXT_STOPWORDS or word in seen: + continue + seen.add(word) + terms.append(word) + + return terms + + +def _text_overlap_score( + patent: model.PatentEntry, + search_terms: list[str], +) -> float: + text = " ".join( + part + for part in [patent.title or "", patent.abstract or ""] + if part + ).casefold() + + if not search_terms or not text.strip(): + return 0.0 + + hits = sum(1 for term in search_terms if term in text) + return min(hits / 3, 1.0) + + +def _patent_passes_relevance_gate( + patent_topics: list[MappedOpenAlexTopic], + *, + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + patent: model.PatentEntry, + text_score: float, +) -> bool: + has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + patent=patent, + ) + return has_topic_match or text_score > 0.0 + + +def _compute_final_score( + ipc_score: float, + topic_score: float, + text_score: float, +) -> float: + return round( + 0.60 * ipc_score + + 0.25 * topic_score + + 0.15 * text_score, + 4, + ) + + +def _score_ipc_match( + patent: model.PatentEntry, + ipc_matches: list[IpcCodeMatch], +) -> tuple[float, list[str], list[str]] | None: + searchable_matches = [ + match + for match in ipc_matches + if match.ipc_level in _SEARCHABLE_IPC_LEVELS + ] or ipc_matches + + best_score = 0.0 + best_keywords: set[str] = set() + best_symbols: set[str] = set() + + patent_codes = [ + normalized + for code in (*patent.ipc, *patent.cpc) + if (normalized := _normalize_ipc_code(code)) + ] + + for ipc_match in searchable_matches: + for patent_code in patent_codes: + hierarchy_quality = _ipc_hierarchy_quality( + patent_code, + ipc_match.ipc_symbol, + ) + if hierarchy_quality <= 0: + continue + + candidate_score = ipc_match.match_score * hierarchy_quality + + if candidate_score > best_score: + best_score = candidate_score + best_keywords = {ipc_match.source_keyword} + best_symbols = {ipc_match.ipc_symbol} + elif math.isclose( + candidate_score, + best_score, + rel_tol=1e-9, + abs_tol=1e-9, + ): + best_keywords.add(ipc_match.source_keyword) + best_symbols.add(ipc_match.ipc_symbol) + + if best_score <= 0: + return None + + return ( + round(best_score, 4), + sorted(best_keywords), + sorted(best_symbols), ) def _score_patent( patent: model.PatentEntry, ipc_matches: list[IpcCodeMatch], + *, + patent_topics: list[MappedOpenAlexTopic] | None = None, + keyword_topic_ids: frozenset[str] | None = None, + keyword_subfield_names: frozenset[str] | None = None, + keyword_soft_field_names: frozenset[str] | None = None, + search_keywords: list[KeywordPatentSearchItem] | None = None, ) -> tuple[float, list[str], list[str]] | None: - best_score = 0.0 - matched_keywords: set[str] = set() - matched_symbols: set[str] = set() + ipc_result = _score_ipc_match(patent, ipc_matches) + if ipc_result is None: + return None + ipc_score, matched_keywords, matched_symbols = ipc_result - patent_codes = [ - normalize_symbol(extract_ipc_symbol(code)) - for code in (*patent.ipc, *patent.cpc) - if extract_ipc_symbol(code) - ] + text_score = 0.0 + if search_keywords is not None: + text_score = _text_overlap_score( + patent, + _text_search_terms(search_keywords), + ) - for ipc_match in ipc_matches: - for patent_code in patent_codes: - if _patent_code_matches_symbol(patent_code, ipc_match.ipc_symbol): - if ipc_match.match_score > best_score: - best_score = ipc_match.match_score - matched_keywords.add(ipc_match.source_keyword) - matched_symbols.add(ipc_match.ipc_symbol) + has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + patent_topics or [], + keyword_topic_ids or frozenset(), + keyword_subfield_names or frozenset(), + keyword_soft_field_names or frozenset(), + patent=patent, + ) - if best_score <= 0: + if not has_topic_match and text_score == 0.0: return None + topic_score = 1.0 if has_topic_match else 0.0 + return ( - best_score, - sorted(matched_keywords), - sorted(matched_symbols), + _compute_final_score(ipc_score, topic_score, text_score), + matched_keywords, + matched_symbols, ) @@ -307,33 +607,78 @@ async def get_patents_by_keywords( reverse_lookup: KeywordIpcReverseLookup | None = None, search_client: BasePatentSearchClient | None = None, ipc_client: IpcSearchClient | None = None, + mapping_resolver: PatentOpenAlexMappingResolver | None = None, ) -> PatentsByKeywordsResponse: lookup = reverse_lookup or KeywordIpcReverseLookup() client = search_client or BasePatentSearchClient() ipc_search = ipc_client or IpcSearchClient() + resolver = mapping_resolver or PatentOpenAlexMappingResolver() queries = IpcPatentSearchQueries() - ipc_matches = await lookup.lookup_ipc_codes( - request.keywords, - max_codes=_MAX_IPC_CODES, - ) - ipc_matches = _filter_ipc_matches_for_search(ipc_matches) - if not ipc_matches: + search_keywords = _filter_keywords_for_patent_search(request.keywords) + if not search_keywords: logger.info( - "Keyword patent search: no IPC codes for keywords %s", + "Keyword patent search: no searchable keywords in %s", [item.keyword for item in request.keywords], ) return PatentsByKeywordsResponse(patent_count=0, patents=[]) + logger.info( + "Keyword patent search: using keywords=%s (from %d requested)", + [ + { + "keyword": item.keyword, + "level": item.keyword_level, + "relevance_score": item.relevance_score, + "field_name": item.field_name, + } + for item in search_keywords + ], + len(request.keywords), + ) + keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names = ( + _keyword_overlap_criteria(search_keywords) + ) + + ipc_matches = await lookup.lookup_ipc_codes( + search_keywords, + max_codes=_MAX_IPC_CODES, + ) + ipc_matches = _filter_ipc_matches_for_search(ipc_matches) + ipc_matches = _limit_matches_per_keyword(ipc_matches) + logger.info( + "Keyword patent search: search_keywords=%s ipc_matches=%s", + [item.keyword for item in search_keywords], + [ + { + "symbol": match.ipc_symbol, + "level": match.ipc_level, + "score": match.match_score, + "keyword": match.source_keyword, + } + for match in ipc_matches + ], + ) + if not ipc_matches: + logger.info( + "Keyword patent search: no IPC codes after filtering for keywords %s", + [item.keyword for item in search_keywords], + ) + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + symbols = _patent_search_terms(ipc_matches) + text_search_terms = _text_search_terms(search_keywords) + logger.info("Keyword patent search: patent_search_terms=%s", symbols) if not symbols: return PatentsByKeywordsResponse(patent_count=0, patents=[]) try: epo_data, uspto_data = await asyncio.gather( - client.search_epo(queries.epo_query_by_ipc_terms(symbols, size=_MAX_PATENTS)), + client.search_epo( + queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) + ), client.search_uspto( - queries.uspto_query_by_ipc_terms(symbols, size=_MAX_PATENTS) + queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) ), ) except MissingApiKeyError: @@ -346,15 +691,64 @@ async def get_patents_by_keywords( raw_patents = deduplicate_patents( parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) ) + logger.info("Keyword patent search: raw_patents=%d", len(raw_patents)) + patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) scored: list[KeywordPatentMatch] = [] + filtered_by_ipc = 0 + filtered_by_relevance_gate = 0 + filtered_by_min_score = 0 for patent in raw_patents: - result = _score_patent(patent, ipc_matches) - if result is None: + patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) + ipc_result = _score_ipc_match(patent, ipc_matches) + if ipc_result is None: + filtered_by_ipc += 1 continue - score, matched_keywords, matched_symbols = result + ipc_score, matched_keywords, matched_symbols = ipc_result + + has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + patent=patent, + ) + + text_score = _text_overlap_score(patent, text_search_terms) + + if not has_topic_match and text_score == 0.0: + filtered_by_relevance_gate += 1 + continue + + topic_score = 1.0 if has_topic_match else 0.0 + + score = _compute_final_score(ipc_score, topic_score, text_score) if score < _MIN_PATENT_MATCH_SCORE: + filtered_by_min_score += 1 continue + + hierarchy_levels = sorted( + { + level + for symbol in matched_symbols + for code in (*patent.ipc, *patent.cpc) + if (level := _ipc_hierarchy_level(code, symbol)) + } + ) + logger.info( + "Patent candidate: id=%s title=%s ipc_score=%.4f " + "topic_score=%.4f text_score=%.4f final_score=%.4f " + "hierarchy_levels=%s matched_keywords=%s matched_symbols=%s", + patent.patent_id, + patent.title, + ipc_score, + topic_score, + text_score, + score, + hierarchy_levels, + matched_keywords, + matched_symbols, + ) scored.append( KeywordPatentMatch( patent=patent, @@ -364,6 +758,15 @@ async def get_patents_by_keywords( ) ) + logger.info( + "Keyword patent search: filtered_by_ipc=%d filtered_by_relevance_gate=%d " + "filtered_by_min_score=%d final_patents=%d", + filtered_by_ipc, + filtered_by_relevance_gate, + filtered_by_min_score, + len(scored), + ) + scored.sort( key=lambda item: ( item.match_score, @@ -372,7 +775,7 @@ async def get_patents_by_keywords( ), reverse=True, ) - scored = _balanced_patent_matches(scored, _MAX_PATENTS) + scored = scored[:_MAX_PATENTS] patents = [item.patent for item in scored] await enrich_patents_classifications(patents, ipc_search) @@ -395,6 +798,7 @@ def keyword_items_from_entries( items.append( KeywordPatentSearchItem( keyword=str(llm.get("keyword") or "").strip(), + keyword_level=entry.get("keyword_level"), topic_id=topic.get("id"), topic_display_name=topic.get("display_name"), subfield_name=(topic.get("subfield") or {}).get("display_name"), diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index 0c435b1c..fe274cad 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -1,10 +1,18 @@ +from typing import Literal + from pydantic import BaseModel, Field from inse.patents.common.model import PatentEntry +KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"] + class KeywordPatentSearchItem(BaseModel): keyword: str = Field(description="Extracted keyword text.") + keyword_level: KeywordPatentLevel | None = Field( + default=None, + description="Keyword granularity from extraction UI: broad, coarse, fine, or custom.", + ) topic_id: str | None = Field( default=None, description="OpenAlex topic id from keyword enrichment, if available.", diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py index 13b9e097..60806eba 100644 --- a/service/src/main/inse/patents/keywords/reverse_lookup.py +++ b/service/src/main/inse/patents/keywords/reverse_lookup.py @@ -10,7 +10,6 @@ import httpx from inse.patents.authors.ipc_openalex_mapping import ( _load_topic_cache, - load_ipc_openalex_mapping, normalize_openalex_id, ) from inse.patents.common.elastic_search_client import MissingApiKeyError @@ -22,82 +21,6 @@ from inse.patents.patents_openalex_keywords.resolver import load_patents_openale logger = logging.getLogger(__name__) -_CS_AI_IPC_SUBCLASSES = ("G06N", "G06F", "G06T", "G06V", "G06K", "G06Q") -_AUTOMOTIVE_IPC_SUBCLASSES = ( - "B60L", - "B60K", - "B60W", - "B60R", - "B60H", - "B60Q", - "B60M", - "F02M", - "F02D", -) -_MEDICINE_IPC_SUBCLASSES = ("A61B", "A61K", "A61M", "A61P", "A61N", "A61F") -_CHEMISTRY_IPC_SUBCLASSES_GENERAL = ("C07C", "C01B", "C08L", "G01N") -_CHEMISTRY_IPC_SUBCLASSES_ORGANIC = ("C07C", "C07D") -_CHEMISTRY_IPC_SUBCLASSES_INORGANIC = ("C01B", "C01G") -_CHEMISTRY_IPC_SUBCLASSES_POLYMER = ("C08L", "C08G") -_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM = ("C12N", "C12Q") -_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL = ("G01N",) -_CHEMISTRY_IPC_SUBCLASSES_PROCESS = ("B01J", "B01D") -_CHEMISTRY_RELATED_SUBFIELDS = frozenset( - { - "organic chemistry", - "inorganic chemistry", - "physical and theoretical chemistry", - "analytical chemistry", - "materials chemistry", - "environmental chemistry", - "biochemistry", - "process chemistry and technology", - "spectroscopy", - "clinical biochemistry", - "geochemistry and petrology", - "pharmaceutical science", - } -) -_CHEMISTRY_RELATED_FIELDS = frozenset( - { - "chemistry", - "chemical engineering", - } -) -_MEDICINE_RELATED_SUBFIELDS = frozenset( - { - "medicine", - "public health", - "health professions", - "pharmacology", - "surgery", - "oncology", - "radiology, nuclear medicine and imaging", - "cardiology and cardiovascular medicine", - "epidemiology", - "immunology", - } -) -_MEDICINE_RELATED_FIELDS = frozenset( - { - "medicine", - "health professions", - "nursing", - "pharmacology, toxicology and pharmaceutics", - "biochemistry, genetics and molecular biology", - } -) -_AI_RELATED_SUBFIELDS = frozenset( - { - "artificial intelligence", - "computer vision and pattern recognition", - "signal processing", - "information systems and management", - "human-computer interaction", - "software", - } -) - _LEVEL_WEIGHTS = { "subgroup": 1.0, "group": 0.92, @@ -135,14 +58,33 @@ def _topic_id_variants(topic_id: str | None) -> list[str]: return list(dict.fromkeys(variants)) +def _topic_id_variants_for_item(item: KeywordPatentSearchItem) -> list[str]: + variants = _topic_id_variants(item.topic_id) + if variants: + return variants + + display_name = (item.topic_display_name or "").strip() + if display_name: + info = _load_topic_cache().get(display_name) + if info and info.get("topic_id"): + return _topic_id_variants(str(info["topic_id"])) + + return [] + + def _weighted_score( ipc_level: str, base_score: float, relevance_score: float, ) -> float: + """Combine IPC mapping confidence with IPC hierarchy level. + + LLM keyword relevance is not applied here: broad keywords often carry + relevance_score 0.0 while still mapping to valid OpenAlex topics. + """ + _ = relevance_score level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7) - relevance = max(relevance_score, 0.1) - return round(base_score * level_weight * relevance, 4) + return round(base_score * level_weight, 4) @lru_cache(maxsize=1) @@ -194,8 +136,6 @@ def _build_json_inverted_index() -> tuple[ def clear_reverse_lookup_caches() -> None: _build_json_inverted_index.cache_clear() - _topic_id_to_hierarchy.cache_clear() - _legacy_indices.cache_clear() def _merge_ipc_match( @@ -228,7 +168,7 @@ def _matches_from_doc( return [] keyword_variants = set(_keyword_variants(item.keyword)) - topic_variants = set(_topic_id_variants(item.topic_id)) + topic_variants = set(_topic_id_variants_for_item(item)) topic_name = (item.topic_display_name or "").strip().casefold() found: list[IpcCodeMatch] = [] @@ -293,7 +233,7 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: merged, level, symbol, score, item.keyword, match_type ) - for variant in _topic_id_variants(item.topic_id): + for variant in _topic_id_variants_for_item(item): for level, symbol, base_score, source_keyword, match_type in by_topic.get( variant, [] ): @@ -305,285 +245,7 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) -@lru_cache(maxsize=1) -def _topic_id_to_hierarchy() -> dict[str, dict[str, str]]: - result: dict[str, dict[str, str]] = {} - for info in _load_topic_cache().values(): - topic_id = info.get("topic_id") - if not topic_id: - continue - for variant in _topic_id_variants(str(topic_id)): - result[variant] = info - return result - - -@lru_cache(maxsize=1) -def _legacy_indices() -> tuple[ - dict[str, list[tuple[str, str, float]]], - dict[str, list[tuple[str, str, float]]], - dict[str, list[tuple[str, str, float]]], - dict[str, list[tuple[str, str, float]]], -]: - """topic_id / topic_name / subfield / field -> (level, symbol, score).""" - by_topic_id: dict[str, list[tuple[str, str, float]]] = {} - by_topic_name: dict[str, list[tuple[str, str, float]]] = {} - by_subfield: dict[str, list[tuple[str, str, float]]] = {} - by_field: dict[str, list[tuple[str, str, float]]] = {} - cache = _load_topic_cache() - - mapping = load_ipc_openalex_mapping() - for level, entries in mapping.items(): - for symbol, mapped in entries.items(): - score = 0.55 - record = (level, normalize_symbol(symbol), score) - for variant in _topic_id_variants(mapped.topic_id): - by_topic_id.setdefault(variant, []).append(record) - if mapped.topic_display_name: - by_topic_name.setdefault( - mapped.topic_display_name.casefold(), [] - ).append(record) - - info = cache.get(mapped.topic_display_name or "") - if info: - subfield = str(info.get("subfield") or "").casefold() - field = str(info.get("field") or "").casefold() - if subfield: - by_subfield.setdefault(subfield, []).append(record) - if field: - by_field.setdefault(field, []).append(record) - - return by_topic_id, by_topic_name, by_subfield, by_field - - -def _hierarchy_for_item(item: KeywordPatentSearchItem) -> dict[str, str]: - for variant in _topic_id_variants(item.topic_id): - info = _topic_id_to_hierarchy().get(variant) - if info: - return info - if item.topic_display_name: - info = _load_topic_cache().get(item.topic_display_name) - if info: - return info - return { - "subfield": item.subfield_name or "", - "field": item.field_name or "", - } - - -def _apply_cs_ai_heuristics( - merged: dict[tuple[str, str], IpcCodeMatch], - item: KeywordPatentSearchItem, -) -> None: - hierarchy = _hierarchy_for_item(item) - subfield = str(hierarchy.get("subfield") or "").casefold() - field = str(hierarchy.get("field") or "").casefold() - if field != "computer science" and subfield not in _AI_RELATED_SUBFIELDS: - return - - for symbol in _CS_AI_IPC_SUBCLASSES: - score = _weighted_score("subclass", 0.62, item.relevance_score) - _merge_ipc_match( - merged, - "subclass", - symbol, - score, - item.keyword, - "heuristic", - ) - - -def _apply_automotive_heuristics( - merged: dict[tuple[str, str], IpcCodeMatch], - item: KeywordPatentSearchItem, -) -> None: - hierarchy = _hierarchy_for_item(item) - subfield = str(hierarchy.get("subfield") or "").casefold() - field = str(hierarchy.get("field") or "").casefold() - keyword = item.keyword.casefold() - automotive_keyword = any( - token in keyword - for token in ( - "automobil", - "fahrzeug", - "kraftfahr", - "elektromob", - "verkehr", - "mobil", - ) - ) - if ( - subfield != "automotive engineering" - and field != "engineering" - and not automotive_keyword - ): - return - - for symbol in _AUTOMOTIVE_IPC_SUBCLASSES: - score = _weighted_score("subclass", 0.6, item.relevance_score) - _merge_ipc_match( - merged, - "subclass", - symbol, - score, - item.keyword, - "heuristic", - ) - - -def _chemistry_subclasses_for_keyword(keyword: str) -> tuple[str, ...]: - normalized = keyword.casefold() - subclasses: list[str] = [] - if any(token in normalized for token in ("anorganisch", "inorganic")): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_INORGANIC) - elif any(token in normalized for token in ("organisch", "organic")): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) - if any(token in normalized for token in ("polymer", "makromolek")): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_POLYMER) - if any(token in normalized for token in ("biochem", "enzym", "ferment")): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM) - if any( - token in normalized - for token in ("analyt", "spektroskop", "chromatograph", "spektromet") - ): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL) - if any( - token in normalized - for token in ("verfahren", "reaktion", "katalys", "synthese", "technische chemie") - ): - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_PROCESS) - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) - if any( - token in normalized - for token in ("chemie", "chemisch", "molekül", "molekul", "stoff") - ): - if not subclasses: - subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_GENERAL) - return tuple(dict.fromkeys(subclasses)) - - -def _apply_chemistry_heuristics( - merged: dict[tuple[str, str], IpcCodeMatch], - item: KeywordPatentSearchItem, -) -> None: - hierarchy = _hierarchy_for_item(item) - subfield = str(hierarchy.get("subfield") or "").casefold() - field = str(hierarchy.get("field") or "").casefold() - subclasses = _chemistry_subclasses_for_keyword(item.keyword) - if ( - subfield not in _CHEMISTRY_RELATED_SUBFIELDS - and field not in _CHEMISTRY_RELATED_FIELDS - and not subclasses - ): - return - - if not subclasses: - subclasses = _CHEMISTRY_IPC_SUBCLASSES_GENERAL - - for symbol in subclasses: - score = _weighted_score("subclass", 0.68, item.relevance_score) - _merge_ipc_match( - merged, - "subclass", - symbol, - score, - item.keyword, - "heuristic", - ) - - -def _apply_medicine_heuristics( - merged: dict[tuple[str, str], IpcCodeMatch], - item: KeywordPatentSearchItem, -) -> None: - hierarchy = _hierarchy_for_item(item) - subfield = str(hierarchy.get("subfield") or "").casefold() - field = str(hierarchy.get("field") or "").casefold() - keyword = item.keyword.casefold() - medicine_keyword = any( - token in keyword - for token in ( - "medizin", - "krankheit", - "therap", - "diagnos", - "patient", - "klinik", - "arzt", - "heilkund", - "pharma", - "immun", - "patholog", - ) - ) - if ( - subfield not in _MEDICINE_RELATED_SUBFIELDS - and field not in _MEDICINE_RELATED_FIELDS - and not medicine_keyword - ): - return - - for symbol in _MEDICINE_IPC_SUBCLASSES: - score = _weighted_score("subclass", 0.72, item.relevance_score) - _merge_ipc_match( - merged, - "subclass", - symbol, - score, - item.keyword, - "heuristic", - ) - - -def _legacy_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: - by_topic_id, by_topic_name, by_subfield, by_field = _legacy_indices() - merged: dict[tuple[str, str], IpcCodeMatch] = {} - - for item in items: - for variant in _topic_id_variants(item.topic_id): - for level, symbol, base_score in by_topic_id.get(variant, []): - score = _weighted_score(level, base_score, item.relevance_score) - _merge_ipc_match( - merged, level, symbol, score, item.keyword, "topic" - ) - - topic_name = (item.topic_display_name or "").strip().casefold() - if topic_name: - for level, symbol, base_score in by_topic_name.get(topic_name, []): - score = _weighted_score(level, base_score, item.relevance_score) - _merge_ipc_match( - merged, level, symbol, score, item.keyword, "topic" - ) - - hierarchy = _hierarchy_for_item(item) - subfield = str(hierarchy.get("subfield") or "").casefold() - field = str(hierarchy.get("field") or "").casefold() - if subfield: - for level, symbol, base_score in by_subfield.get(subfield, []): - score = _weighted_score(level, base_score * 0.85, item.relevance_score) - _merge_ipc_match( - merged, level, symbol, score, item.keyword, "subfield" - ) - if field: - for level, symbol, base_score in by_field.get(field, []): - score = _weighted_score(level, base_score * 0.7, item.relevance_score) - _merge_ipc_match( - merged, level, symbol, score, item.keyword, "field" - ) - - results = sorted(merged.values(), key=lambda match: match.match_score, reverse=True) - if not results: - logger.info( - "Legacy IPC lookup found no codes for %d keyword(s); " - "build patents_openalex_keywords for better coverage.", - len(items), - ) - return results - - -def _finalize_ipc_matches( - items: list[KeywordPatentSearchItem], - matches: list[IpcCodeMatch], -) -> list[IpcCodeMatch]: +def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: merged: dict[tuple[str, str], IpcCodeMatch] = {} for match in matches: _merge_ipc_match( @@ -594,11 +256,6 @@ def _finalize_ipc_matches( match.source_keyword, match.match_type, ) - for item in items: - _apply_cs_ai_heuristics(merged, item) - _apply_automotive_heuristics(merged, item) - _apply_chemistry_heuristics(merged, item) - _apply_medicine_heuristics(merged, item) return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) @@ -620,7 +277,7 @@ def _build_es_should_clauses(items: list[KeywordPatentSearchItem]) -> list[dict[ } ) - for topic_id in _topic_id_variants(item.topic_id): + for topic_id in _topic_id_variants_for_item(item): if topic_id in seen: continue seen.add(topic_id) @@ -695,21 +352,15 @@ class KeywordIpcReverseLookup: if not matches: matches = _json_lookup(items) - if not matches: - matches = _legacy_lookup(items) - if not matches: logger.info( - "No IPC codes resolved for keywords: %s", + "No IPC codes resolved for keywords: %s; " + "build patents_openalex_keywords for better coverage.", [item.keyword for item in items], ) - matches = _finalize_ipc_matches(items, matches) - heuristics = [match for match in matches if match.match_type == "heuristic"] - regular = [match for match in matches if match.match_type != "heuristic"] - regular = sorted(regular, key=lambda match: match.match_score, reverse=True) - remaining = max(0, max_codes - len(heuristics)) - return heuristics + regular[:remaining] + matches = _dedupe_ipc_matches(matches) + return matches[:max_codes] async def _lookup_via_elasticsearch( self, diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 74817c6c..cb6dda70 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -1,24 +1,115 @@ """Tests for keyword-based patent search.""" from __future__ import annotations +import asyncio +from unittest.mock import AsyncMock, patch + +from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common import model -from inse.patents.keywords.logic import _patent_code_matches_symbol, _score_patent +from inse.patents.keywords.logic import ( + _compute_final_score, + _filter_keywords_for_patent_search, + _ipc_hierarchy_quality, + _keyword_is_patent_searchable, + _limit_matches_per_keyword, + _patent_passes_relevance_gate, + _patent_search_terms, + _score_ipc_match, + _score_patent, + _term_from_ipc_match, + _text_overlap_score, + _text_search_terms, + _topics_overlap_keywords, + get_patents_by_keywords, +) from inse.patents.keywords.reverse_lookup import ( IpcCodeMatch, - _finalize_ipc_matches, _json_lookup, - _legacy_lookup, _weighted_score, clear_reverse_lookup_caches, ) -from inse.patents.keywords.model import KeywordPatentSearchItem -from inse.patents.keywords.search_queries import _search_terms_for_symbol +from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest +from inse.patents.keywords.search_queries import IpcPatentSearchQueries, _search_terms_for_symbol -def test_patent_code_matches_symbol_prefix() -> None: - assert _patent_code_matches_symbol("G01S 5/02", "G01S") - assert _patent_code_matches_symbol("G01S5/02", "G01S") - assert not _patent_code_matches_symbol("H01L 21/02", "G01S") +def test_ipc_hierarchy_quality_exact_match() -> None: + assert _ipc_hierarchy_quality("C07C243/08", "C07C243/08") == 1.0 + + +def test_ipc_hierarchy_quality_same_main_group() -> None: + assert _ipc_hierarchy_quality("C07C243/086", "C07C243/088") == 0.90 + + +def test_ipc_hierarchy_quality_same_subclass() -> None: + assert _ipc_hierarchy_quality("C07C243/08", "C07C31/20") == 0.75 + + +def test_ipc_hierarchy_quality_no_match() -> None: + assert _ipc_hierarchy_quality("C07C243/08", "C08F110/10") == 0.0 + + +def test_ipc_hierarchy_quality_invalid_code() -> None: + assert _ipc_hierarchy_quality("", "C07C243/08") == 0.0 + assert _ipc_hierarchy_quality("C07", "C07C243/08") == 0.0 + + +def test_term_from_ipc_match_returns_subclass() -> None: + match = IpcCodeMatch("subgroup", "C07C243/08", 0.9, "Organic Chemistry", "keyword") + assert _term_from_ipc_match(match) == "C07C" + + +def test_term_from_ipc_match_skips_class_level() -> None: + match = IpcCodeMatch("class", "C07", 0.7, "Chemistry", "topic") + assert _term_from_ipc_match(match) is None + + +def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None: + ipc_matches = [ + IpcCodeMatch("subgroup", "C25B3/03", 0.9037, "Anorganische Chemie", "keyword"), + IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"), + IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"), + IpcCodeMatch("subgroup", "D06L4/17", 0.8745, "Technische Chemie", "keyword"), + IpcCodeMatch("subgroup", "C09B43/34", 0.8738, "Chemische Reaktionen", "keyword"), + IpcCodeMatch("subgroup", "C02F1/285", 0.8698, "Organische Chemie", "keyword"), + IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"), + ] + terms = _patent_search_terms(ipc_matches) + assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"] + + +def test_score_ipc_match_returns_only_best_evidence() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["C07C243/08"], + ) + ipc_matches = [ + IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"), + IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"), + ] + result = _score_ipc_match(patent, ipc_matches) + assert result is not None + score, keywords, symbols = result + assert score == 0.8989 + assert keywords == ["Anorganische Chemie"] + assert symbols == ["C07C243/08"] + + +def test_score_ipc_match_keeps_equal_best_matches() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["C07C243/08"], + ) + ipc_matches = [ + IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"), + IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"), + ] + result = _score_ipc_match(patent, ipc_matches) + assert result is not None + _, keywords, symbols = result + assert keywords == ["Anorganische Chemie", "Organische Chemie"] + assert symbols == ["C07C243/08"] def test_score_patent_uses_best_ipc_match() -> None: @@ -26,22 +117,426 @@ def test_score_patent_uses_best_ipc_match() -> None: patent_id="EP123", source="EPO", ipc=["G01S 5/02"], + title="Wireless localization system", ) ipc_matches = [ IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"), IpcCodeMatch("class", "G01", 0.5, "wireless", "topic"), ] - result = _score_patent(patent, ipc_matches) + result = _score_patent( + patent, + ipc_matches, + patent_topics=[ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T12345", + subfield_name="Remote Sensing", + ) + ], + keyword_topic_ids=frozenset({"T12345"}), + search_keywords=[ + KeywordPatentSearchItem( + keyword="wireless localization", + topic_id="https://openalex.org/T12345", + relevance_score=1.0, + ) + ], + ) assert result is not None score, keywords, symbols = result - assert score == 0.9 + assert score == _compute_final_score(0.675, 1.0, 2 / 3) assert "localization" in keywords assert "G01S" in symbols -def test_weighted_score_applies_level_and_relevance() -> None: - score = _weighted_score("subclass", 0.8, 0.5) - assert score == round(0.8 * 0.85 * 0.5, 4) +def test_score_patent_requires_topic_overlap() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["G01S 5/02"], + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"), + ] + patent_topics = [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + subfield_name="Oncology", + ) + ] + result = _score_patent( + patent, + ipc_matches, + patent_topics=patent_topics, + keyword_topic_ids=frozenset({"T12345"}), + keyword_subfield_names=frozenset({"law"}), + ) + assert result is None + + +def test_score_patent_accepts_compatible_engineering_and_computer_science() -> None: + patent = model.PatentEntry( + patent_id="EP456", + source="EPO", + ipc=["G06N 3/08"], + title="Deep learning classifier", + abstract="A neural network for classification tasks.", + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G06N", 0.9, "Deep Learning", "keyword"), + ] + result = _score_patent( + patent, + ipc_matches, + patent_topics=[ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T12072", + field_name="Computer Science", + ) + ], + keyword_topic_ids=frozenset({"T10653"}), + keyword_subfield_names=frozenset({"control and systems engineering"}), + keyword_soft_field_names=frozenset({"engineering"}), + search_keywords=[ + KeywordPatentSearchItem( + keyword="Deep Learning", + topic_id="https://openalex.org/T10653", + field_name="Engineering", + relevance_score=0.9, + ) + ], + ) + assert result is not None + + +def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None: + items = [ + KeywordPatentSearchItem( + keyword="Naturwissenschaft", + keyword_level="broad", + relevance_score=1.0, + topic_id="https://openalex.org/T14329", + field_name="Environmental Science", + ), + KeywordPatentSearchItem( + keyword="Thermodynamik", + keyword_level="coarse", + relevance_score=0.8, + topic_id="https://openalex.org/T12345", + field_name="Physics and Astronomy", + subfield_name="Statistical and Nonlinear Physics", + ), + KeywordPatentSearchItem( + keyword="noise", + keyword_level="coarse", + relevance_score=0.0, + ), + ] + filtered = _filter_keywords_for_patent_search(items) + assert [item.keyword for item in filtered] == ["Thermodynamik"] + + +def test_filter_keywords_for_patent_search_allows_zero_relevance_with_topic() -> None: + item = KeywordPatentSearchItem( + keyword="Deep Learning", + keyword_level="fine", + relevance_score=0.0, + topic_id="https://openalex.org/T12072", + field_name="Computer Science", + subfield_name="Artificial Intelligence", + ) + assert _keyword_is_patent_searchable(item) + + +def test_filter_keywords_for_patent_search_allows_high_relevance_with_technical_topic() -> None: + items = [ + KeywordPatentSearchItem( + keyword="Deep Learning", + keyword_level="fine", + relevance_score=0.9, + topic_id="https://openalex.org/T12072", + field_name="Computer Science", + subfield_name="Artificial Intelligence", + ), + ] + filtered = _filter_keywords_for_patent_search(items) + assert [item.keyword for item in filtered] == ["Deep Learning"] + + +def test_topics_overlap_keywords_soft_match_engineering_and_computer_science() -> None: + patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["G06N 3/08"]) + patent_topics = [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T12072", + field_name="Computer Science", + ) + ] + assert _topics_overlap_keywords( + patent_topics, + frozenset({"T10653"}), + frozenset({"control and systems engineering"}), + frozenset({"engineering"}), + patent=patent, + ) + + +def test_score_patent_accepts_matching_topic_id() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["G01S 5/02"], + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"), + ] + patent_topics = [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T12345", + subfield_name="Remote Sensing", + ) + ] + result = _score_patent( + patent, + ipc_matches, + patent_topics=patent_topics, + keyword_topic_ids=frozenset({"T12345"}), + ) + assert result is not None + + +def test_topics_overlap_keywords_uses_subfield_name_not_field() -> None: + patent_topics = [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + subfield_name="Chemistry", + field_name="Physical Sciences", + ) + ] + assert not _topics_overlap_keywords( + patent_topics, + frozenset(), + frozenset({"law"}), + frozenset(), + ) + assert _topics_overlap_keywords( + patent_topics, + frozenset(), + frozenset({"chemistry"}), + frozenset(), + ) + assert _topics_overlap_keywords( + patent_topics, + frozenset(), + frozenset(), + frozenset({"physical sciences"}), + ) + assert not _topics_overlap_keywords( + patent_topics, + frozenset(), + frozenset(), + frozenset({"engineering"}), + ) + + +def test_topics_overlap_keywords_rejects_patents_without_topics() -> None: + assert not _topics_overlap_keywords( + [], + frozenset({"T12345"}), + frozenset(), + frozenset({"chemistry"}), + ) + + +def test_limit_matches_per_keyword() -> None: + matches = [ + IpcCodeMatch("subclass", "C07C", 0.95, "Organic Chemistry", "keyword"), + IpcCodeMatch("group", "C07C31", 0.9, "Organic Chemistry", "keyword"), + IpcCodeMatch("subclass", "C01B", 0.88, "Inorganic Chemistry", "keyword"), + IpcCodeMatch("subclass", "C01C", 0.87, "Inorganic Chemistry", "keyword"), + ] + limited = _limit_matches_per_keyword(matches, limit=2) + assert len(limited) == 4 + organic = [match for match in limited if match.source_keyword == "Organic Chemistry"] + inorganic = [match for match in limited if match.source_keyword == "Inorganic Chemistry"] + assert len(organic) == 2 + assert len(inorganic) == 2 + assert organic[0].ipc_symbol == "C07C" + assert inorganic[0].ipc_symbol == "C01B" + + +def test_text_overlap_score_uses_title_and_abstract() -> None: + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Organic chemistry synthesis", + abstract="A method for catalytic reactions.", + ) + score = _text_overlap_score( + patent, + ["organic", "chemistry", "catalytic", "reactions", "unrelated"], + ) + assert score == 1.0 + + +def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None: + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Diagnostic imaging device", + abstract="Medical diagnosis using imaging.", + ) + assert _patent_passes_relevance_gate( + [], + keyword_topic_ids=frozenset({"T99999"}), + keyword_subfield_names=frozenset(), + keyword_soft_field_names=frozenset({"medicine"}), + patent=patent, + text_score=_text_overlap_score(patent, ["diagnostic", "imaging", "diagnosis"]), + ) + + +def test_patent_passes_relevance_gate_rejects_ipc_only() -> None: + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Humidifier system", + abstract="Water exchange membrane.", + ) + assert not _patent_passes_relevance_gate( + [], + keyword_topic_ids=frozenset({"T99999"}), + keyword_subfield_names=frozenset(), + keyword_soft_field_names=frozenset({"medicine"}), + patent=patent, + text_score=0.0, + ) + + +def test_compute_final_score_weights_ipc_topic_and_text() -> None: + assert _compute_final_score(0.9, 1.0, 1.0) == round( + 0.60 * 0.9 + 0.25 * 1.0 + 0.15 * 1.0, + 4, + ) + assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4) + + +def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None: + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + ipc=["C07C31/20"], + title="Humidifier system", + abstract="Water exchange membrane.", + ) + ipc_matches = [ + IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"), + ] + result = _score_patent( + patent, + ipc_matches, + patent_topics=[], + keyword_topic_ids=frozenset({"T99999"}), + keyword_soft_field_names=frozenset({"chemistry"}), + search_keywords=[ + KeywordPatentSearchItem( + keyword="Organische Chemie", + topic_id="https://openalex.org/T99999", + field_name="Chemistry", + relevance_score=1.0, + ) + ], + ) + assert result is None + + +def test_get_patents_by_keywords_uses_symbol_queries() -> None: + queries = IpcPatentSearchQueries() + captured: list[str] = [] + + async def fake_search_epo(query): + captured.append("epo") + assert "query" in query + return {"hits": {"hits": []}} + + async def fake_search_uspto(query): + captured.append("uspto") + return {"hits": {"hits": []}} + + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="Organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/T13859", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock( + return_value=[ + IpcCodeMatch( + "subgroup", + "C07C243/08", + 0.8989, + "Organische Chemie", + "keyword", + ) + ] + ), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=fake_search_epo), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(side_effect=fake_search_uspto), + ), patch( + "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", + new=AsyncMock(return_value={}), + ), patch( + "inse.patents.keywords.logic.enrich_patents_classifications", + new=AsyncMock(), + ), patch.object( + IpcPatentSearchQueries, + "epo_query_by_ipc_symbols", + wraps=queries.epo_query_by_ipc_symbols, + ) as epo_symbols, patch.object( + IpcPatentSearchQueries, + "uspto_query_by_ipc_symbols", + wraps=queries.uspto_query_by_ipc_symbols, + ) as uspto_symbols: + asyncio.run(get_patents_by_keywords(request)) + + epo_symbols.assert_called_once() + uspto_symbols.assert_called_once() + assert epo_symbols.call_args.args[0] == ["C07C"] + assert captured == ["epo", "uspto"] + + +def test_text_search_terms_include_topic_metadata() -> None: + items = [ + KeywordPatentSearchItem( + keyword="Organische Chemie", + topic_display_name="Organic Chemistry", + subfield_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=0.9, + topic_id="https://openalex.org/T1", + ) + ] + terms = _text_search_terms(items) + assert "organische" in terms + assert "organic" in terms + assert "chemistry" in terms + + +def test_weighted_score_applies_level_not_llm_relevance() -> None: + score_high = _weighted_score("subclass", 0.8, 1.0) + score_zero = _weighted_score("subclass", 0.8, 0.0) + assert score_high == round(0.8 * 0.85, 4) + assert score_zero == score_high def test_search_terms_use_subclass_prefix() -> None: @@ -49,47 +544,16 @@ def test_search_terms_use_subclass_prefix() -> None: assert "G06N" in _search_terms_for_symbol("G06N") -def test_legacy_lookup_uses_chemistry_heuristics() -> None: +def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() - items = [ - KeywordPatentSearchItem( - keyword="Organische Chemie", - relevance_score=1.0, - ) - ] - matches = _finalize_ipc_matches(items, _legacy_lookup(items)) - symbols = {match.ipc_symbol for match in matches} - assert "C07C" in symbols - - -def test_legacy_lookup_uses_medicine_heuristics() -> None: + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", + lambda: {}, + ) clear_reverse_lookup_caches() - items = [ - KeywordPatentSearchItem( - keyword="Medizin", - relevance_score=1.0, - ) - ] - matches = _finalize_ipc_matches(items, _legacy_lookup(items)) - symbols = {match.ipc_symbol for match in matches} - assert "A61B" in symbols - -def test_legacy_lookup_uses_cs_ai_heuristics() -> None: - clear_reverse_lookup_caches() - items = [ - KeywordPatentSearchItem( - keyword="Klassifikation", - topic_id="https://openalex.org/T12072", - topic_display_name="Machine Learning and Algorithms", - subfield_name="Artificial Intelligence", - field_name="Computer Science", - relevance_score=1.0, - ) - ] - matches = _finalize_ipc_matches(items, _legacy_lookup(items)) - symbols = {match.ipc_symbol for match in matches} - assert "G06N" in symbols + items = [KeywordPatentSearchItem(keyword="Medizin", relevance_score=1.0)] + assert _json_lookup(items) == [] def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None: @@ -126,3 +590,83 @@ def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None: assert len(matches) == 1 assert matches[0].ipc_symbol == "G01S" assert matches[0].match_score > 0 + + +def test_json_lookup_finds_ipc_for_topic_id(monkeypatch) -> None: + clear_reverse_lookup_caches() + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", + lambda: { + "subclass": { + "G06N": { + "ipc_level": "subclass", + "ipc_symbol": "G06N", + "keyword_matches": [], + "topic_matches": [ + { + "topic_id": "https://openalex.org/T12072", + "topic_display_name": "Machine Learning and Algorithms", + "match_score": 0.88, + } + ], + } + } + }, + ) + clear_reverse_lookup_caches() + + items = [ + KeywordPatentSearchItem( + keyword="Klassifikation", + topic_id="https://openalex.org/T12072", + topic_display_name="Machine Learning and Algorithms", + relevance_score=1.0, + ) + ] + matches = _json_lookup(items) + assert len(matches) == 1 + assert matches[0].ipc_symbol == "G06N" + assert matches[0].match_type == "topic" + + +def test_json_lookup_resolves_topic_id_from_display_name(monkeypatch) -> None: + clear_reverse_lookup_caches() + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", + lambda: { + "subclass": { + "G01N": { + "ipc_level": "subclass", + "ipc_symbol": "G01N", + "keyword_matches": [], + "topic_matches": [ + { + "topic_id": "https://openalex.org/T14329", + "topic_display_name": "Science and Climate Studies", + "match_score": 0.9, + } + ], + } + } + }, + ) + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup._load_topic_cache", + lambda: { + "Science and Climate Studies": { + "topic_id": "https://openalex.org/T14329", + } + }, + ) + clear_reverse_lookup_caches() + + items = [ + KeywordPatentSearchItem( + keyword="Science and Climate Studies", + topic_display_name="Science and Climate Studies", + relevance_score=1.0, + ) + ] + matches = _json_lookup(items) + assert len(matches) == 1 + assert matches[0].ipc_symbol == "G01N" diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index e2b8921a..8af22a4b 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -1,7 +1,10 @@ import { PatentEntry } from './patentEntry'; +export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; + export interface KeywordPatentSearchItem { keyword: string; + keyword_level?: KeywordPatentLevel | null; topic_id?: string | null; topic_display_name?: string | null; subfield_name?: string | null; diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 6d96b219..a2649375 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -1,114 +1,132 @@ -@if (loading()) { -

Lade passende Patente...

-} @else if (error()) { -

Fehler beim Laden der Patente.

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

Keine passenden Patente gefunden.

-} @else { -
-

Passende Patente

- -
-
-
- -
- - - - - - - - - - - @for (item of pagedMatches(); track trackMatch($index, item)) { - - - - - - } - -
PatentQuelleJahr
- {{ item.patent.title ?? item.patent.patent_id }} - - - {{ item.patent.source }} - - {{ item.patent.publication_year ?? '-' }}
- - @if (hasPagination()) { - - } -
- - @if (selectedPatent(); as patent) { -
-

{{ patent.title ?? patent.patent_id }}

-
-
- Quelle - - - {{ patent.source }} - - -
-
- Patent-Nr. - {{ patent.patent_id }} -
-
- Datum - {{ - formatDate(patent.publication_date) - }} -
- @if (getPublicationStageLabel(patent); as stageLabel) { -
- Publikationsstufe - {{ stageLabel }} -
- } -
- - -
- } -
-
-} +@if (loading()) { +

Lade passende Patente...

+} @else if (error()) { +

Fehler beim Laden der Patente.

+} @else if (matches().length === 0) { +

Keine passenden Patente gefunden.

+} @else { +
+

Passende Patente

+ +
+
+
+ +
+ + + + + + + + + + + + @for (item of pagedMatches(); track trackMatch($index, item)) { + + + + + + + } + +
PatentScoreQuelleJahr
+ {{ item.patent.title ?? item.patent.patent_id }} + {{ formatScore(item.match_score) }} + + {{ item.patent.source }} + + {{ item.patent.publication_year ?? '-' }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedMatch(); as match) { +
+

{{ match.patent.title ?? match.patent.patent_id }}

+
+
+ Match-Score + {{ formatScore(match.match_score) }} +
+
+ Gematchte Keywords + {{ + formatMatchList(match.matched_keywords) + }} +
+
+ Gematchte IPC/CPC + {{ + formatMatchList(match.matched_ipc_symbols) + }} +
+
+ Quelle + + + {{ match.patent.source }} + + +
+
+ Patent-Nr. + {{ match.patent.patent_id }} +
+
+ Datum + {{ + formatDate(match.patent.publication_date) + }} +
+ @if (getPublicationStageLabel(match.patent); as stageLabel) { +
+ Publikationsstufe + {{ stageLabel }} +
+ } +
+ + +
+ } +
+
+} diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index be8b1c24..d700ff61 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -113,12 +113,23 @@ margin: 12px 0; } +.match-score { + font-variant-numeric: tabular-nums; + color: #374151; + white-space: nowrap; +} + .stat-label { display: block; font-size: 12px; color: #666; } +.stat-value { + display: block; + word-break: break-word; +} + .patent-detail-action { display: flex; align-items: center; diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index 4d11c1a2..8b1b26d8 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -1,88 +1,103 @@ -import { Component, input, signal } from '@angular/core'; -import { Router } from '@angular/router'; -import { PatentEntry } from '../../../api/model/patentEntry'; -import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse'; -import { - formatPatentDate, - getPublicationStageLabel, -} from '../../patent-detail/patent-detail.utils'; - -type SourceFilter = 'all' | 'EPO' | 'USPTO'; - -@Component({ - selector: 'app-keywords-patents', - templateUrl: './keywords-patents.component.html', - styleUrl: './keywords-patents.component.scss', -}) -export class KeywordsPatentsComponent { - readonly matches = input([]); - readonly loading = input(false); - readonly error = input(false); - - activeFilter = signal('all'); - selectedPatent = signal(null); - selectedPage = signal(1); - readonly pageSize = 10; - - constructor(private readonly router: Router) {} - - filteredMatches(): KeywordPatentMatch[] { - const filter = this.activeFilter(); - const items = this.matches(); - if (filter === 'all') { - return items; - } - return items.filter((item) => item.patent.source === filter); - } - - pagedMatches(): KeywordPatentMatch[] { - const start = (this.selectedPage() - 1) * this.pageSize; - return this.filteredMatches().slice(start, start + this.pageSize); - } - - pageCount(): number { - return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize)); - } - - hasPagination(): boolean { - return this.pageCount() > 1; - } - - setFilter(filter: SourceFilter): void { - this.activeFilter.set(filter); - this.selectedPage.set(1); - this.selectedPatent.set(null); - } - - setPage(page: number): void { - this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); - } - - selectPatent(patent: PatentEntry): void { - this.selectedPatent.set(patent); - } - - openDetail(): void { - const patent = this.selectedPatent(); - if (!patent) return; - void this.router.navigate(['/patent', patent.patent_id]); - } - - formatDate(date: string | null | undefined): string { - return formatPatentDate(date); - } - - getPublicationStageLabel(patent: PatentEntry): string | null { - return getPublicationStageLabel(patent); - } - - trackMatch(_index: number, item: KeywordPatentMatch): string { - const patent = item.patent; - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } -} +import { Component, input, signal } from '@angular/core'; +import { Router } from '@angular/router'; +import { PatentEntry } from '../../../api/model/patentEntry'; +import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../../patent-detail/patent-detail.utils'; + +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-keywords-patents', + templateUrl: './keywords-patents.component.html', + styleUrl: './keywords-patents.component.scss', +}) +export class KeywordsPatentsComponent { + readonly matches = input([]); + readonly loading = input(false); + readonly error = input(false); + + activeFilter = signal('all'); + selectedMatch = signal(null); + selectedPage = signal(1); + readonly pageSize = 10; + + constructor(private readonly router: Router) {} + + filteredMatches(): KeywordPatentMatch[] { + const filter = this.activeFilter(); + const items = this.matches(); + if (filter === 'all') { + return items; + } + return items.filter((item) => item.patent.source === filter); + } + + pagedMatches(): KeywordPatentMatch[] { + const start = (this.selectedPage() - 1) * this.pageSize; + return this.filteredMatches().slice(start, start + this.pageSize); + } + + pageCount(): number { + return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize)); + } + + hasPagination(): boolean { + return this.pageCount() > 1; + } + + setFilter(filter: SourceFilter): void { + this.activeFilter.set(filter); + this.selectedPage.set(1); + this.selectedMatch.set(null); + } + + setPage(page: number): void { + this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); + } + + selectMatch(item: KeywordPatentMatch): void { + this.selectedMatch.set(item); + } + + openDetail(): void { + const match = this.selectedMatch(); + if (!match) return; + void this.router.navigate(['/patent', match.patent.patent_id]); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + formatScore(score: number | null | undefined): string { + if (score == null || Number.isNaN(score)) { + return '-'; + } + return score.toFixed(2); + } + + formatMatchList(values: string[] | null | undefined): string { + if (!values || values.length === 0) { + return '-'; + } + return values.join(', '); + } + + trackMatch(_index: number, item: KeywordPatentMatch): string { + const patent = item.patent; + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + item.match_score, + ].join('|'); + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 217ca43f..088edbd0 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -58,6 +58,7 @@ import { SearchResultsPayload } from './search-results/search-results-state.serv type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; +type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; @Component({ selector: 'app-keywords-search', imports: [ @@ -1109,11 +1110,9 @@ export class KeywordsSearchComponent { } private loadMatchingPatents(): void { - const entries = [ - ...this.getSelectedExtractedKeywordEntries(), - ...this.getSelectedManualKeywordEntries(), - ]; - const keywords = this.buildPatentSearchItems(entries); + const keywords = this.buildPatentSearchItems( + this.getSelectedPatentKeywordEntries(), + ); if (keywords.length === 0) { this.patentMatches.set([]); this.patentsLoaded.set(true); @@ -1139,12 +1138,39 @@ export class KeywordsSearchComponent { }); } + private getSelectedPatentKeywordEntries(): Array<{ + entry: KeywordEntryWithTopic; + level: KeywordPatentLevel; + }> { + const selected = new Set( + this.selectedKeywords().map((k) => this.normalizeKeyword(k)), + ); + const isSelected = (item: KeywordEntryWithTopic) => + selected.has(this.normalizeKeyword(this.getKeywordLabel(item))); + + return [ + ...this.broadKeywordEntries() + .filter(isSelected) + .map((entry) => ({ entry, level: 'broad' as const })), + ...this.coarseKeywordEntries() + .filter(isSelected) + .map((entry) => ({ entry, level: 'coarse' as const })), + ...this.fineKeywordEntries() + .filter(isSelected) + .map((entry) => ({ entry, level: 'fine' as const })), + ...this.manualKeywordEntries() + .filter(isSelected) + .map((entry) => ({ entry, level: 'custom' as const })), + ]; + } + private buildPatentSearchItems( - entries: KeywordEntryWithTopic[], + items: Array<{ entry: KeywordEntryWithTopic; level: KeywordPatentLevel }>, ): KeywordPatentSearchItem[] { - return entries - .map((entry) => ({ + return items + .map(({ entry, level }) => ({ keyword: entry.llm_keyword.keyword, + keyword_level: level, topic_id: entry.topic_mapping?.topic?.id ?? null, topic_display_name: entry.topic_mapping?.topic?.display_name ?? null, subfield_name: entry.topic_mapping?.topic?.subfield?.display_name ?? null, From 010e1c7f213da963b1bd3c901603b628093ba16b Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 10 Jul 2026 13:43:08 +0200 Subject: [PATCH 32/60] publications: sort author publications by citations or year --- service/src/main/inse/works/logic.py | 4 ++++ service/src/main/inse/works/search_client.py | 18 ++++++++++---- service/src/main/inse/works/service.py | 7 +++++- .../src/main/inse/works/test_search_client.py | 22 +++++++++++++++++ webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/works.service.ts | 10 ++++++++ webapp/src/app/api/model/matchedTopic.ts | 18 ++++++++++++++ webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/newsArticleDetail.ts | 3 ++- .../person-publications.component.html | 13 ++++++++++ .../person-publications.component.scss | 4 ++++ .../person-publications.component.ts | 24 +++++++++++++++++++ 12 files changed, 119 insertions(+), 6 deletions(-) create mode 100644 webapp/src/app/api/model/matchedTopic.ts diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 96bf0ef2..ec4f16af 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -55,6 +55,7 @@ async def get_author_works( language: list[str] | None = None, institution_id: list[str] | None = None, topic_id: list[str] | None = None, + sort: str = "year", client: OpenAlexWorksSearchClient | None = None, ) -> WorkPage: search_client = client or OpenAlexWorksSearchClient() @@ -68,6 +69,7 @@ async def get_author_works( language=language, institution_id=institution_id, topic_id=topic_id, + sort=sort, ) elements, total = _parse_full_work_search_response(data) @@ -929,6 +931,7 @@ async def _search_author_works_data( language: list[str] | None = None, institution_id: list[str] | None = None, topic_id: list[str] | None = None, + sort: str = "year", ) -> dict: return await search_client.search_author_works( author_id, @@ -939,6 +942,7 @@ async def _search_author_works_data( language=language, institution_id=institution_id, topic_id=topic_id, + sort=sort, ) diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 42b2ee8b..2e52a9a6 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -35,6 +35,7 @@ class OpenAlexWorksSearchClient: language: list[str] | None = None, institution_id: list[str] | None = None, topic_id: list[str] | None = None, + sort: str = "year", ) -> dict[str, Any]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" filters = self._work_filters( @@ -73,6 +74,16 @@ class OpenAlexWorksSearchClient: }, }, }) + if sort == "citations": + sort_clauses = [ + {"cited_by_count": {"order": "desc", "missing": "_last"}}, + {"publication_year": {"order": "desc", "missing": "_last"}}, + ] + else: + sort_clauses = [ + {"publication_year": {"order": "desc", "missing": "_last"}}, + {"cited_by_count": {"order": "desc", "missing": "_last"}}, + ] return { "from": (page - 1) * size, "size": size, @@ -83,10 +94,7 @@ class OpenAlexWorksSearchClient: "filter": filters, }, }, - "sort": [ - {"publication_year": {"order": "desc", "missing": "_last"}}, - {"cited_by_count": {"order": "desc", "missing": "_last"}}, - ], + "sort": sort_clauses, } def _work_filters( @@ -130,6 +138,7 @@ class OpenAlexWorksSearchClient: language: list[str] | None = None, institution_id: list[str] | None = None, topic_id: list[str] | None = None, + sort: str = "year", ) -> dict[str, Any]: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") @@ -143,6 +152,7 @@ class OpenAlexWorksSearchClient: language=language, institution_id=institution_id, topic_id=topic_id, + sort=sort, ) return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,) diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 382f3fd7..ead6daad 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -4,7 +4,7 @@ REST API for publication works. """ -from typing import Annotated, Optional +from typing import Annotated, Literal, Optional from fastapi import APIRouter from fastapi import Path @@ -54,6 +54,10 @@ async def get_author_works( list[str] | None, Query(description="Filter by OpenAlex topic id. Can be repeated."), ] = None, + sort: Annotated[ + Literal["year", "citations"], + Query(description="Sort order: by publication year or by citation count."), + ] = "year", ): return await logic.get_author_works( author_id, @@ -64,6 +68,7 @@ async def get_author_works( language=language, institution_id=institution_id, topic_id=topic_id, + sort=sort, ) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 2d9e2a41..1f3c905e 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -26,6 +26,28 @@ def test_author_works_query_searches_authorship_author_id(): assert query["query"]["bool"]["filter"] == [] +def test_author_works_query_sorts_by_year_by_default(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query("A5023888391", page=1, size=20) + + assert query["sort"] == [ + {"publication_year": {"order": "desc", "missing": "_last"}}, + {"cited_by_count": {"order": "desc", "missing": "_last"}}, + ] + + +def test_author_works_query_sorts_by_citations(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query("A5023888391", page=1, size=20, sort="citations") + + assert query["sort"] == [ + {"cited_by_count": {"order": "desc", "missing": "_last"}}, + {"publication_year": {"order": "desc", "missing": "_last"}}, + ] + + def test_author_works_query_adds_publication_filters(): client = OpenAlexWorksSearchClient(api_key="test-key") diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 9928d2c3..e0efeecf 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -142,6 +142,7 @@ model/loginResponse.ts model/longitude.ts model/matchedAuthor.ts model/matchedOfficer.ts +model/matchedTopic.ts model/mentionedPerson.ts model/meta.ts model/model2YrMeanCitedness.ts diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index ca494a80..4561cb78 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -165,6 +165,7 @@ export class WorksService extends BaseService { * @param language Filter by language code. Can be repeated. * @param institutionId Filter by OpenAlex institution id. Can be repeated. * @param topicId Filter by OpenAlex topic id. Can be repeated. + * @param sort Sort order: by publication year or by citation count. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -177,6 +178,7 @@ export class WorksService extends BaseService { language?: Array, institutionId?: Array, topicId?: Array, + sort?: 'year' | 'citations', observe?: 'body', reportProgress?: boolean, options?: { @@ -194,6 +196,7 @@ export class WorksService extends BaseService { language?: Array, institutionId?: Array, topicId?: Array, + sort?: 'year' | 'citations', observe?: 'response', reportProgress?: boolean, options?: { @@ -211,6 +214,7 @@ export class WorksService extends BaseService { language?: Array, institutionId?: Array, topicId?: Array, + sort?: 'year' | 'citations', observe?: 'events', reportProgress?: boolean, options?: { @@ -228,6 +232,7 @@ export class WorksService extends BaseService { language?: Array, institutionId?: Array, topicId?: Array, + sort?: 'year' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: { @@ -298,6 +303,11 @@ export class WorksService extends BaseService { ); }); } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sort, + 'sort', + ); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/matchedTopic.ts b/webapp/src/app/api/model/matchedTopic.ts new file mode 100644 index 00000000..52de9018 --- /dev/null +++ b/webapp/src/app/api/model/matchedTopic.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface MatchedTopic { + id?: string | null; + display_name?: string | null; + subfield_name?: string | null; + field_name?: string | null; + domain_name?: string | null; + source_keyword?: string | null; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index d932a058..fb8ac2ef 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -117,6 +117,7 @@ export * from './loginResponse'; export * from './longitude'; export * from './matchedAuthor'; export * from './matchedOfficer'; +export * from './matchedTopic'; export * from './mentionedPerson'; export * from './meta'; export * from './model2YrMeanCitedness'; diff --git a/webapp/src/app/api/model/newsArticleDetail.ts b/webapp/src/app/api/model/newsArticleDetail.ts index ac51097c..09962000 100644 --- a/webapp/src/app/api/model/newsArticleDetail.ts +++ b/webapp/src/app/api/model/newsArticleDetail.ts @@ -7,6 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { MatchedTopic } from './matchedTopic'; import { MentionedPerson } from './mentionedPerson'; export interface NewsArticleDetail { @@ -20,6 +21,6 @@ export interface NewsArticleDetail { related?: boolean | null; full_content?: string | null; authors?: Array; - topics?: Array; keywords?: Array; + topics?: Array; } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index ba311a44..1b1664bb 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -156,6 +156,19 @@ + + sort + + @for (option of sortOptions; track option.value) { + {{ option.label }} + } + + +
- @if (worksCount() !== null || citedByCount() !== null) { + @if ( + worksCount() !== null || citedByCount() !== null || h_index() !== null + ) { @if (worksCount() !== null) { menu_book - {{ worksCount() }} Publikationen + {{ worksCount() | number }} Publikationen } @if (worksCount() !== null && citedByCount() !== null) { @@ -45,50 +47,66 @@ @if (citedByCount() !== null) { format_quote - {{ citedByCount() }} Zitationen + {{ citedByCount() | number }} Zitationen + + } + @if ( + (worksCount() !== null || citedByCount() !== null) && + h_index() !== null + ) { + · + } + @if (h_index() !== null) { + + trending_up + h-Index {{ h_index() }} } - - @if (h_index() !== null) { - h_index: {{ h_index() }} + } + @if (displayCareerStage() || orcid()) { + -
-
- mail - uni-email@uni-due.de -
- @if (orcid()) { -
- verified - {{ - orcid() - }} -
- } - -